开发者

Objective-C: Instance Variable in Category

开发者 https://www.devze.com 2023-03-09 10:44 出处:网络
I am just asking whether it was possible to add an instance variable via a category. My special problem is, that I need to add an NSIndexPath property to an ASIHTTPRequest object but I don\'t wanna su

I am just asking whether it was possible to add an instance variable via a category. My special problem is, that I need to add an NSIndexPath property to an ASIHTTPRequest object but I don't wanna subclass the ASIHTTPRequest a开发者_开发问答s a matter of principle.

Do I have any kind of alternative?

Thanks for your answers, Christian


A category can not declare additional instance variables but since OS X 10.6 and iOS 3.1 you can work around this with associative references.

You can use associative references to simulate the addition of object instance variables to an existing class. Using associative references, you can add storage to an object without modifying the class declaration. This is done via objc_setAssociatedObject and objc_getAssociatedObject. If you wrap these calls in a property’s custom getter and setter, you can fake an ivar.

Have a look at this post by Ole Begemann.

0

精彩评论

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

关注公众号