runtime - iOS 中 分类关联实例属性的写法有点疑问?
PHP中文网
PHP中文网 2017-04-18 09:52:09
0
3
660
- (NSString *)associatedObject_copy {
    return objc_getAssociatedObject(self, _cmd);
}

- (void)setAssociatedObject_copy:(NSString *)associatedObject_copy {
    objc_setAssociatedObject(self, @selector(associatedObject_copy), associatedObject_copy, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

上面这段代码中, _cmdself 类似,只不过前者表示的是当前的SEL
第二个方法的第二个参数为什么不也用_cmd呢?我理解的 _cmd@selector(当前方法)不是一个意思吗?
为什么第一个方法的第二个参数用_cmd,第二个方法的第二个参数却用@selector(xxx)了啊?
希望能告知一二.....

啰嗦这么多:

其实我的问题主要是 在同一个方法里面,_cmd@selector(当前方法) 完全一样嘛?不一样,有什么区别?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
Peter_Zhu

Because to bind the same property setter and getter must be the same key,但是用_cmd只能获取当前的方法名,所以你在set方法里面肯定要或获取跟上面相同的key, _cmd也是SEL类型的参数和@selector(xxx) same

左手右手慢动作

The second parameter of objc_getAssociatedObject and objc_setAssociatedObject is just a key

id objc_getAssociatedObject(id object, const void *key);

Of course, you can use @selector() as a parameter. Its essence is also a constant id. You also said above that your _cmd is also a SEL. Logically speaking, the second parameter of your objc_setAssociatedObject should be _cmd. Generally, Usage is defined as follows:


static const void *YourKeyName  = &YourKeyName;
阿神

_cmd can only get the name of the current method. If you also use _cmd in set, you will get "setAssociatedObject_copy".

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template