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. SVN trunk(主线) branch(分支) tag(标记) 用法详解和详细操作步骤

    使用场景: 假如你的项目(这里指的是手机客户端项目)的某个版本(例如1.0版本)已经完成开发.测试并已经上线了,接下来接到新的需求,新需求的开发需要修改多个文件中的代码,当需求已经开始开发一段时间的时 ...

  2. github上老外做的jQuery虚拟键盘

    jQuery官方比较迟滞的更新版本: http://plugins.jquery.com/keyboard/ 最新版本更新官方地址: https://github.com/Mottie/Keyboar ...

  3. [C语言] 数据结构-预备知识动态内存分配

    动态内存分配 静态内存分配数组 int a[5]={1,2,3,4,5}  动态内存分配数组 int len=5; int *parr=(int *)malloc(sizeof(int) * len) ...

  4. mysql中的坑

    1,MySQL建表中double类型不能限制数据长度! 2,……

  5. AngularJS之过滤器

    AnularJS的过滤器用来格式化需要展示给用户的数据,有很多实用的内置过滤器,也可以自己编写. 在HTML中的模板绑定符号{{ }}内通过|符号来调用过滤器.例如,假设我们希望将字符串转换成大写,可 ...

  6. jQuery源码学习笔记一

    学习jQuery源码,我主要是通过妙味视频上学习的.这里将所有的源码分析,还有一些自己弄懂过程中的方法及示例整理出来,供大家参考. 我用的jquery v2.0.3版本. var rootjQuery ...

  7. 如何去掉iview里面的input,button等一系列标签自带的蓝色边框

    只需要将这些标签加一个:focus{outline:0}即可解决这个问题

  8. Spring Boot—18Redis

    pom.xml <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-ja ...

  9. Evernote Markdown Sublime使用介绍

    版权声明: 欢迎转载,但请保留文章原始出处 作者:GavinCT 出处:http://www.cnblogs.com/ct2011/p/4002619.html 这一篇博客继续探讨:Evernote ...

  10. linux erlang环境安装

    1.安装环境:yum -y install make gcc gcc-c++ kernel-devel m4 glibc-devel autoconfyum -y install ncurses-de ...