Avoid extra static variables for associated objects keys

前端 未结 3 459
刺人心
刺人心 2020-12-08 02:36

When using associated objects, an Objective-C runtime feature available starting from iOS 4 and OSX 10.6, it\'s necessary to define a key for storing and retrieving the obje

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 03:23

    If you need access to the key from outside the scope of a single method, a nice pattern for this which leads to more readable code is to create a pointer which simply points to its own address in the stack. For example:

    static void const *MyAssocKey = &MyAssocKey;
    

    If you only need access from within the scope of a single method, you can actually just use _cmd, which is guaranteed to be unique. For example:

    objc_setAssociatedObject(obj, _cmd, associatedObj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    

提交回复
热议问题