加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift 中的 Selector 类型

发布时间:2020-12-14 01:54:43 所属栏目:百科 来源:网络整理
导读:Cocoa Touch Framework 中有很多地方需要用到Selector类型,例如: UIButton - addTarget:action:forControlEvents: NSTimer - scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: NSNotificationCenter - addObserver:selector:name:object
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)
}

@objc func 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读