search

Home  >  Q&A  >  body text

runtime - iOS 中 分类关联实例属性的写法有点疑问?

- (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中文网2771 days ago661

reply all(3)I'll reply

  • 天蓬老师

    天蓬老师2017-04-18 09:54:09

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

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 09:54:09

    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;
    

    reply
    0
  • 阿神

    阿神2017-04-18 09:54:09

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

    reply
    0
  • Cancelreply