azamsharp
azamsharp

Reputation: 20094

UIView Categories and Properties

I am trying to extend the UIView class to include a setUserData method which will hold the object values or any value. Here is the declaration:

userData is defined as an id property in the .h file.

@implementation UIView (Extensions) 

@synthesize userData;

-(void) setUserData:(id)value
{
    self.userData = value; 
}

@end

Of course xCode complains that I cannot use @synthesize in categories. How can I achieve this task or maybe there is already some property in UIView which can hold an object. Just like the tag property but tag property only holds integars.

Upvotes: 3

Views: 875

Answers (1)

Joshua Weinberg
Joshua Weinberg

Reputation: 28688

As you stated, you can't synthesize properties in a category. To achieve this you'd have to use an Obj-C runtime features called associated objects.

#import <objc/runtime.h>

const char * const viewKey = "jweinberg.view.storage";

@implementation UIView (Storage)

- (id)myProperty;
{
    return objc_getAssociatedObject(self, viewKey);
}

- (void)setMyProperty:(id)property;
{
    objc_setAssociatedObject(self, viewKey, property, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

Upvotes: 5

Related Questions