15

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 as a matter of principle.

Do I have any kind of alternative?

Thanks for your answers, Christian

cschwarz
  • 1,195
  • 11
  • 24
  • possible duplicate of [Objective-C: Property in Category](http://stackoverflow.com/questions/8733104/objective-c-property-in-category) – hfossli Jan 16 '14 at 08:24

1 Answers1

19

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.

Community
  • 1
  • 1
albertamg
  • 28,492
  • 6
  • 64
  • 71
  • Thanks, but just found an easier solution: userInfo-Dictionary in ASIHTTPRequest! But anyway, thanks! – cschwarz May 28 '11 at 15:38
  • 1
    I'm happy you solved it! You may want to answer the question yourself with your solution and accept it or accept one of the other answers so the question does not remain unaccepted. – albertamg May 28 '11 at 18:15
  • 1
    It is in fact now possible to add ivars in a class extension. See: http://stackoverflow.com/questions/5826345/how-to-declare-instance-variables-and-methods-not-visible-or-usable-outside-of-th/5826453#5826453 – jscs May 28 '11 at 18:24
  • That would require to synthesize/implement accessors of the property in the main @implementation block for the corresponding class – albertamg May 28 '11 at 20:55
  • 1
    anyone have a correct url for the `associative references` link? – progrmr Feb 27 '13 at 18:04