Question

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.

Was it helpful?

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

OTHER TIPS

Why do you think this means multiple implementations of udid?

If you have classes A, B, C, etc. which inherit from NSObject and you switch them all to inherit from NSObjectWithUDID instead then there is just one implementation of udid - and it is implemented for you by the compiler.

You are correct, adding a property using a category is non-trivial - but it can be done using associated objects. However there appears to be no need to go that route here.

HTH

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top