@objc协议崩溃了swift编译器

时间:2014-07-03 23:46:45

标签: ios swift ios7

我编写了I协议,该协议旨在使用一些@optional方法,但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足以让编译器崩溃。有没有解决方法?

2 个答案:

答案 0 :(得分: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"

在Swift中符合类实现:

// Session.swift

class Session {
    // ...
}

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

答案 1 :(得分: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.
    }
}