tags:

views:

19

answers:

2

we know that using category we can add functions to existing class. But i have a doubt that, Is it possible to add objects or data members to category in objective C ??

A: 

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.

Toastor
You can use Objective-C associated objects. See my answer.
Mike Weller
+1  A: 

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.

Mike Weller
But this is limited to objects that you manually add, right? After all, the big advantage of categories is that you don't need to worry about which object will be able to use the added functionality...
Toastor
Well presumably you want to add a property to an existing class using a category. To do that you simply define the setter/getter to use objc_setAssociatedObject etc. instead of @synthesizing the property.
Mike Weller