Search code examples
objective-cpropertiesruntimeobjective-c-categoryassociated-object

What is the benefit of using associated objects vs static object defined in the category implementation file?


The problem is I don't see the benefit of using associated objects vs static objects defined in the category implementation file with getter/setter methods.

I was thinking about defining the getters and setters in the header file of the category. Like this:

@interface NSObject (test_static)

- (id)getStaticObject;
- (void)setStaticObject:(id)a_static;

@end

and then to declare a static variable in the implementation file and implement getter/setter methods, like this:

static id test;

@implementation NSObject (test_static)

- (id)getStaticObject
{
    return test;
}

- (void)setStaticObject:(id)a_static
{
    test = a_static;
}

Why I shouldn't use this approach and use associated objects instead ?

Well, I guess I didn't get how properties work and how they've solved the fragile base class problem. Maybe it's related...


Solution

  • There is a huge difference. Associated objects is a way to simulate properties in a category.

    Using a single static variable means you have a single, shared value used across all instances.

    The choice is which to use depends on your goal. If you want an instance specific result from your two category methods, do not use a static variable - use associated objects. If you want the same object back from the two category methods regardless of the object instance, then use the static variable (and probably change your category methods to class methods instead of instance methods).