Adding custom behavior and state to all my classes

2019-09-02 17:28发布

问题:

I want to add functionality and another property to ALL of my classes.


So I wrote a category:

@implementation NSObject (MyCategory)

And I declared a static property in it:

static MyObj myObj;

And I created 2 class methods to get and set it:

+ (MyObj) getMyObj {
    return myObj;
}

+ (void) setMyObj:(MyObj)obj {
    myObj = obj;
}

Now I imported NSObject+MyCategory.h in my .pch file, so all classes will be effected by this. Indeed all classes now have the new functionality and state:

#import "NSObject+MyCategory.h"

The problem is that when I set myObj, it changes myObj on all classes. All classes share 1 myObj.

I want each class to have its own myObj that is added using the category. I don't want one myObj, rather I want as many myObj's as classes. Each class should have its own myObj.

Thanks, Nur

回答1:

You can not add properties instance variables to a class in categories. Either subclass NSObject or use associated objects.



回答2:

Your solution adds a single static variable (not "property", in Objective-C that means something else), there is no way using categories to add a static variable per class.

However your idea is close to what will work for you; if you can only have one variable and want to store many values what can you use? A dictionary.

static NSMutableDictionary *References;

+ (void) load
{
   // load is called exactly once when this category is first loaded,
   // setup the dictionary
   References = [NSMutableDictionary new];
}

+ (void) setMyObj:(MyObj)reference
{
   // NSMutableDictionary will take any object reference as a key,
   // for a class method self is a reference to the unique class object,
   // so use self as the key and store the reference
   [References setObject:reference forKey:self];
}

+ (MyObj) getMyObj
{
   // returns previously stored reference or nil if there isn't one for this class
   return [References objectForKey:self];
}

HTH