我有一个Objective C类,其方法如下所示:
@class Client;
@protocol ClientDelegate <NSObject>
@optional
-(void) receivedMessageFromClient : (id) message;
@end
@interface Client : NSObject
+(id) setup;
@property(nonatomic, strong) id <ClientDelegate> clientDelegate;
// more method declarations below
我正在我的Swift类中实现ClientDelegate,如下所示:
class HomeViewController: UIViewController, ClientDelegate {
var client : AnyObject?
var delegate: ClientDelegate?
override func viewDidLoad() {
super.viewDidLoad()
client = Client.setup() as! Client
client.clientDelegate = self
}
func receivedMessageFromClient(message: AnyObject) {
print("Message recieved: \(message)")
}
}
这给了我一个编译错误:
无法分配属性:&#39; self&#39;是不可改变的
删除行
client = Client.setup() as! Client
client.clientDelegate = self
代码编译并调用Client类中的方法,该方法又将消息发送到receivedMessageFromClient
,但该方法未在HomeViewController
中调用。除了将self指定为委托之外,似乎所有设置都已设置。
答案 0 :(得分:7)
查看我对您的问题的评论,但这是在Swift中实现的Objective-C委托的基本示例:
目标-C:
@protocol MyDelegate <NSObject>
@optional
- (void)canImplementThis:(int)aVar;
@required
- (BOOL)needToImplementThis;
@end
@interface MyClass : NSObject
@property (nonatomic, weak) id<MyDelegate> delegate;
@end
夫特:
class SwiftClass : UIViewController, MyDelegate {
var myObj : MyClass?
override func viewDidLoad() {
super.viewDidLoad()
myObj = MyClass()
myObj?.delegate = self
}
// MARK: - <MyDelegate>
func canImplementThis(aVar : Int) {
print("Called: \(aVar))
}
func needToImplementThis() -> Bool {
return false
}
}
原谅我输入的任何拼写错误直接进入SO。
答案 1 :(得分:0)
由于某种原因必须将Int更改为Int32,因此它修复了无效的选择器问题,在快速端使用Int32然后工作