swift 中的 Selector 类型

来源:互联网 发布:p2p对等网络监管 编辑:程序博客网 时间:2024/06/10 01:15
Cocoa Touch Framework 中有很多地方需要用到Selector类型,例如:
UIButton -  addTarget:action:forControlEvents:
NSTimer - scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
NSNotificationCenter - addObserver:selector:name:object:
UIGestureRecognizer - initWithTarget:action:

swift 中的Selector使用方法很简单:
class DailyShowData {
   init() {
       NSNotificationCenter.defaultCenter().addObserver(self, selector:"onKrDownloaded:", name: "FinishedNotification", object:nil)
    }

   @objcfunc onKrDownloaded(noti:NSNotification) {
    }
}

说明:
1. 在Objective-C 中的 @selector(onKrDownloaded:) 变成了 onKrDownloaded: ,就是用双引号替换了@selector,内部的写法和Objective-C完全相同。 
2. 函数定义时,要加上 @objc 前缀。因为,最终执行时,是从Objc运行时调用swift中的函数。 

Apple有份文档“Using Swift with Cocoa and Objective-C”,本来没想仔细看。 最初以为,在一个swift工程中,可能会用到一些Objc的库,也就是在swift中调用Objc的类,做一个bridge header就可以了。 从Objc中调用swift代码的机会应该很少,真正做起来才发现,只要用到Cocoa Touch framework,Objc与swift的各种交互无处不在。

看来需要好好看看这份文档了:
https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html#//apple_ref/doc/uid/TP40014216-CH4-XID_26
0 0
原创粉丝点击