2014-07-03 64 views
2

我寫了I協議,它的目的是有一些@optional方法,但swift編譯器崩潰。這工作:@objc協議崩潰swift編譯器

protocol SessionDelegate { 

    // TODO these should all be optional 
    func willOpenSession(session: Session); 
    func didOpenSession(session: Session); 
    func didFailOpenningSession(session: Session, error: NSError!); 

    func willCloseSession(session: Session); 
    func didCloseSession(session: Session); 
} 

這不:

@objc protocol SessionDelegate { 

    @optional func willOpenSession(session: Session); 
    @optional func didOpenSession(session: Session); 
    @optional func didFailOpenningSession(session: Session, error: NSError!); 

    @optional func willCloseSession(session: Session); 
    @optional func didCloseSession(session: Session); 
} 

老實說,有@objc足以崩潰的編譯器。有什麼解決方法嗎?

+0

您的協議是否必須擴展NSObject協議? –

+0

嘿,你有'Session'聲明爲'NSObject'的子類嗎? –

回答

1

現在,您唯一的解決方法是在Objective-C頭文件中聲明協議並通過Objective-C橋接頭導入聲明。

協議聲明:

// SessionDelegate.h 

@class Session; 

@protocol SessionDelegate <NSObject> 

@optional 

- (void)willOpenSession:(Session *)session; 
- (void)didOpenSession:(Session *)session; 
- (void)didFailOpenningSession:(Session *)session error:(NSError *)error; 

- (void)willCloseSession:(Session *)session; 
- (void)didCloseSession:(Session *)session; 

@end 

橋接報頭:在夫特

// MyProject-Bridging-Header.h 

#import "SessionDelegate.h" 

符合類實現:

// Session.swift 

class Session { 
    // ... 
} 

class MySessionDelegate: NSObject, SessionDelegate { 
    func willOpenSession(session: Session) { 
     // ... 
    } 
} 
+0

工作就像一個魅力!我從來沒有學過Objective-C,所以感謝代碼;) –

+0

你能看到我的其他問題嗎?它是相關的:http://stackoverflow.com/questions/24591921/sessiondelegate-does-not-have-a-member-named-xxx –

1

道歉,從我以前的編輯劃傷,請嘗試以下代替:

@objc(PSessionDelegate) 
protocol PSessionDelegate { 

    @optional func willOpenSession(session: Session); 
    @optional func didOpenSession(session: Session); 
    @optional func didFailOpenningSession(session: Session, error: NSError!); 
    @optional func willCloseSession(session: Session); 
    @optional func didCloseSession(session: Session); 

} 

class ViewController: UIViewController, PSessionDelegate { 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 

    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 
} 
+0

不,我只是試圖使協議方法可選。純粹快捷,沒有任何目標-C。 –

+0

@AndréFratelli,代碼在iOS 7.1設備上測試過,沒有崩潰,有趣的是你的代碼沒有崩潰。 – vladof81

+0

我的代碼崩潰了編譯器,所以它沒有得到iOS ...我會嘗試你的答案,因爲它很快,儘管@Nate Cook的解決方案已經工作=) –