Instance Variables for Objective C Categories

前端 未结 8 1830
终归单人心
终归单人心 2020-12-02 15:43

I have a situation where it seems like I need to add instance variables to a category, but I know from Apple\'s docs that I can\'t do that. So I\'m wondering what the best a

相关标签:
8条回答
  • 2020-12-02 16:23

    I believe it is now possible to add synthesized properties to a category and the instance variables are automagically created, but I've never tried it so I'm not sure if it will work.

    A more hacky solution:

    Create a singleton NSDictionary which will have the UIViewController as the key (or rather its address wrapped as an NSValue) and the value of your property as its value.

    Create getter and setter for the property that actually goes to the dictionary to get/set the property.

    @interface UIViewController(MyProperty)
    
    @property (nonatomic, retain) id myProperty;
    @property (nonatomic, readonly, retain) NSMutableDcitionary* propertyDictionary;
    
    @end
    
    @implementation  UIViewController(MyProperty)
    
    -(NSMutableDictionary*) propertyDictionary
    {
        static NSMutableDictionary* theDictionary = nil;
        if (theDictionary == nil)
        {
            theDictioanry = [[NSMutableDictionary alloc] init];
        }
        return theDictionary;
    }
    
    
    -(id) myProperty
    {
        NSValue* key = [NSValue valueWithPointer: self];
        return [[self propertyDictionary] objectForKey: key];
    }
    
    -(void) setMyProperty: (id) newValue
    {
        NSValue* key = [NSValue valueWithPointer: self];
        [[self propertyDictionary] setObject: newValue forKey: key];    
    }
    
    @end
    

    Two potential problems with the above approach:

    • there's no way to remove keys of view controllers that have been deallocated. As long as you are only tracking a handful, that shouldn't be a problem. Or you could add a method to delete a key from the dictionary once you know you are done with it.
    • I'm not 100% certain that the isEqual: method of NSValue compares content (i.e. the wrapped pointer) to determine equality or if it just compares self to see if the comparison object is the exact same NSValue. If the latter, you'll have to use NSNumber instead of NSValue for the keys (NSNumber numberWithUnsignedLong: will do the trick on both 32 bit and 64 bit platforms).
    0 讨论(0)
  • 2020-12-02 16:25

    Why not simply create a subclass of UIViewController, add the functionality to that, then use that class (or a subclass thereof) instead?

    0 讨论(0)
提交回复
热议问题