开发者

Is it possible to add objects or data members to category in objective C?

we know that using category we can add functions to existing class. But i have a doubt that, Is it possible to add object开发者_如何学Gos or data members to category in objective C ??


You can use Objective-C associated references. You can read the Apple documentation about them here: Associative References

Basically this lets you attach objects to any instance using the objc_setAssociatedObject function as follows:

#import <objc/runtime.h>

/* The key for the associated object must be void* so you can use a static variable to get a
   unique pointer. Alternatively you can use _cmd since selectors are constant and unique. */
static char key;
objc_setAssociatedObject(theInstanceToAddYourObjectTo,
                         &key,
                         @"The object you want to add",
                         OBJC_ASSOCIATION_RETAIN);

To get the associated object again:

id value = objc_getAssociatedObject(theInstanceToAddYourObjectTo, &key);

And to clear the associated object, pass nil as the value:

objc_setAssociatedObject(theInstanceToAddYourObjectTo,
                         &key,
                         nil,
                         OBJC_ASSOCIATION_ASSIGN);

So using these functions you can add your own instance variables for use in category methods etc.


You're right, you cannot add instance variables / members / properties via a category. You can only work with what the class you're expanding already offers, but of course your new methods may receive arguments upon being called.


The problem is that with associated objects is not possible to access it from method

  - (void)encodeWithCoder:(NSCoder *)aCoder
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜