Search code examples
iosobjective-cinheritancensobjectudid

iOS how to introduce an ability for a class to have UDID without subclassing everything?


I'm working with keyed archiving and found that there's a need for some of my objects to have universal identifier. I'm thinking of introducing UDID for this purpose.

I can create a custom class like this and have my objects inherit from this, but this means multiple implementations of udid. I would like to have only one.

@interface NSObjectWithUDID : NSObject

@property(nonatomic,strong,readonly)NSString* udid;

@end

My question is: How can I add an ability for my classes to respond to [udid] message without having to subclass NSObjectWithUDID?

I tried categories, but am not sure if I can use a property there.


Solution

  • You are right that you cant add a property in a Category, but you can do a runtime set using objc runtime methods

    #import <objc/runtime.h>
    static char udidKey;
    
    @implementation NSObject (UDIDAddition)
    
    - (NSString *)udid {
       return objc_getAssociatedObject(self, &udidKey);
    }
    
    - (void)setUdid:(NSString *)udid {
        objc_setAssociatedObject(self, &udidKey, udid, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    @end