Some Objective-C APIs—like target-action—accept method or property names as parameters, then use those names to dynamically call or access the methods or properties. In Swift, you use the #selector and #keyPath expressions to represent those method or property names as selectors or key paths, respectively.

https://developer.apple.com/documentation/swift/using_objective-c_runtime_features_in_swift

一、@objc应用于函数是为了能够让函数表达为 #selector;

In Objective-C, a selector is a type that refers to the name of an Objective-C method. In Swift, Objective-C selectors are represented by the Selector structure, and you create them using the #selector expression.

import UIKit

class MyViewController: UIViewController {

let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))

override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) {

super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)

let action = #selector(MyViewController.tappedButton)

myButton.addTarget(self, action: action, forControlEvents: .touchUpInside)

}

@objc func tappedButton(_ sender: UIButton?) {

print("tapped button")

}

required init?(coder: NSCoder) {

super.init(coder: coder)

}

二、@objc应用于变量是为了能够让变量表达为keypath字符串,进而使用kvc功能。

class Person: NSObject {

@objc var name: String

@objc var friends: [Person] = []

@objc var bestFriend: Person? = nil

init(name: String) {

self.name = name

}

}

let gabrielle = Person(name: "Gabrielle")

let jim = Person(name: "Jim")

let yuanyuan = Person(name: "Yuanyuan")

gabrielle.friends = [jim, yuanyuan]

gabrielle.bestFriend = yuanyuan

#keyPath(Person.name)

// "name"

gabrielle.value(forKey: #keyPath(Person.name))

// "Gabrielle"

#keyPath(Person.bestFriend.name)

// "bestFriend.name"

gabrielle.value(forKeyPath: #keyPath(Person.bestFriend.name))

// "Yuanyuan"

#keyPath(Person.friends.name)

// "friends.name"

gabrielle.value(forKeyPath: #keyPath(Person.friends.name))

三、@objc dynamic应用于变量是为了让变量能够使用kvo机制。

class MyObjectToObserve: NSObject {

@objc dynamic var myDate = NSDate(timeIntervalSince1970: 0) // 1970

func updateDate() {

myDate = myDate.addingTimeInterval(Double(2 << 30)) // Adds about 68 years.

}

}

class MyObserver: NSObject {

@objc var objectToObserve: MyObjectToObserve

var observation: NSKeyValueObservation?

init(object: MyObjectToObserve) {

objectToObserve = object

super.init()

observation = observe(

\.objectToObserve.myDate,

options: [.old, .new]

) { object, change in

print("myDate changed from: \(change.oldValue!), updated to: \(change.newValue!)")

}

}

}

let observed = MyObjectToObserve()

let observer = MyObserver(object: observed)

observed.updateDate() // Triggers the observer's change handler.

// Prints "myDate changed from: 1970-01-01 00:00:00 +0000, updated to: 2038-01-19

Here’s the least you need to remember:

  • @objc makes things visible to Objective-C code. You might need this for setting up target/action on buttons and gesture recognizers.
  • dynamic opts into dynamic dispatch. You might need this for KVO support or if you‘re doing method swizzling.
  • The only way to do dynamic dispatch currently is through the Objective-C runtime, so you must add @objc if you use dynamic.

https://www.cnblogs.com/feng9exe/p/9460336.html

@objc vs @objc dynamic官方解释的更多相关文章

  1. 零宽度正预测先行断言是什么呢,看msdn上的官方解释定义

    最近为了对html文件进行源码处理,需要进行正则查找并替换.于是借着这个机会把正则系统地学一下,虽然以前也用过正则,但每次都是临时学一下混过关的.在学习的过程中还是遇到不少问题的,特别是零宽断言(这里 ...

  2. 为什么我刚发表的文章变成了“待审核”,csdn有没有官方解释啊

    为什么我刚发表的文章变成了"待审核",csdn有没有官方解释啊,什么样的文章才会变为待审核呢? 并且从草稿箱和回收站里也看不到我的文章了,希望我的文章没有删掉. 文章的字是一个个打 ...

  3. @Resource注解的官方解释

    一.@Resource注解的官方解释@Resource annotation, which is semantically defined to identify a specific target ...

  4. SDE在64位Server2008下Post启动服务失败官方解释

    解决了一个SDE启动问题,在此记录一下 在server 2008 64位下安装完arcgis sde之后,Post启动服务,总是失败 查看SDE日志(etc目录下) DB_open_instance( ...

  5. cocos2d-x 3.0 touch事件官方解释

    官方解释 http://www.cocos2d-x.org/docs/manual/framework/native/input/event-dispatcher/zh#_1

  6. WM_ERASEBKGND官方解释(翻译),以及Delphi里所有的使用情况(就是绘制窗口控件背景色,并阻止进一步传递消息)

    #define WM_ERASEBKGND                   0x0014 Parameters wParam A handle to the device context. //  ...

  7. MATLAB ' : ' 官方解释

    1.冒号的作用 产生矢量,阵列标注以及for-loop迭代子 2.描述 冒号是MATLAB中最有用的操作符之一.它使用下述规则来创建有规则的空间矢量: j:k is the same as [j,j+ ...

  8. Android USER 版本与ENG 版本的差异--MTK官方解释

     分类: Android(4)  Description]Android USER 版本与ENG 版本的差异 [Keyword]USER ENG user eng 用户版本 工程版本 差异 [Solu ...

  9. zabbix3.4.7官方解释触发器

    函数   描述 参数 说明 abschange   最近获取值与之前获取值差的绝对值.   支持值的类型: float, int, str, text, log 例如: (最近获取值;之前获取值=ab ...

随机推荐

  1. 我用ASP.NET缓存之OutputCache

    [我的理解]页面缓存常用在网站上.Web应用系统上也用,但由于Web系统常与数据库打交道.时效性要求蛮强的,所以是否能用缓存得具体情况具体分析(很喜欢这句话“具体情况具体分析”,很符合国人的中庸之道) ...

  2. JavaScript unshift()怎样添加数据的?

    var a = new Array(); a.unshift("red", "green"); a.unshift("black"); 这个 ...

  3. 微信获取openId

    router.beforeEach(function(to, from, next){ //中间页等待跳转 if(to.meta.requireCheck=="WaitLogin" ...

  4. Maven + Spring4

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...

  5. FineReport中如何用JavaScript解决控件值刷新不及时

    我们经常利用按钮进行一些页面值的处理工作,但是默认的逻辑造成,每次新填报的值,需要点击下空白区域或是执行某个其他操作才可以被正确读取,那么我们如何处理呢? 例:当我们用常规取值的时候,虽然B3单元格录 ...

  6. Dialog中更新Activity的数据显示

    假设有一个activity,activity中有一个Button和一个TextView,点击按钮,弹出Dialog,对话框中有一个ListView,选中ListView中的某一项,关闭对话框,更新ac ...

  7. Pwn Heap With Tcache

    Pwn Heap With Tcache 前言 glibc 2.26 开始引入了 tcache , 相关的 commit 可以看 这里 .加入 tcache 对性能有比较大的提升,不过由于 tcach ...

  8. FastDFS部署安装全过程

    你好!欢迎阅读我的博文,你可以跳转到我的个人博客网站,会有更好的排版效果和功能. 此外,本篇博文为本人Pushy原创,如需转载请注明出处:https://pushy.site/posts/153205 ...

  9. canvas验证码 - 滑块拼图

    滑块拼图型的验证方式已经流行起来,多数的实现方式是直接加载两张分割好的图片.现在用canvas去自动修剪图片,节省修图工作量和http请求: 加载一张整图,用canvas切割缺口,缺口位置在固定范围内 ...

  10. eclipse maven构建的java web工程项目 在修改了工程项目名时,tomcat启动异常java.lang.IllegalArgumentException: Can't convert argument:null

    问题 我修改了前一个项目的名称.重新启动该项目至tomcat,报错:Java.lang.IllegalArgumentException: Can't convert argument: null 因 ...