Roger
Roger

Reputation: 773

I want to set an arbitrary key:value property on a UIView

For my iOS program, I want to set an arbitrary key:value property on a UIView. I couldn't find any way to do this. Any ideas?

Upvotes: 2

Views: 2466

Answers (3)

ftvs
ftvs

Reputation: 438

Layers are key-value compliant, according to https://stackoverflow.com/a/400251/264619 (go upvote that answer), so you could set key:values on a view's layers instead.

UIView *myView = [[UIView alloc] init];
[myView.layer setValue: @"hello" forKey: @"world"];

Upvotes: 7

rob mayoff
rob mayoff

Reputation: 385640

Attach an NSMutableDictionary to the UIView using objc_setAssociatedObject.

http://developer.apple.com/library/ios/ipad/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocAssociativeReferences.html

Upvotes: 3

user529758
user529758

Reputation:

A common approach is to use the receiver's memory address as a key in a dictionary, and set subsequent, embedded ditionaries for those keys:

#define KEY(o) [NSString stringWithFormat:@"%x", o]

- (id) init
{
    if ((self = [super init])
    {
        // other stuff
        NSMutableDictionary *globalKeys = [NSMutableDictionary new]; // don't forget to release in dealloc
    }
    return self;
}

// and where you want to set a key-value pair:
- (void) addKey:(NSString *)key value:(id)value forObject:(id)obj
{
    NSString *objKey = KEY(obj);
    NSDictionary *objDict = [globalKeys objectForKey:objKey];
    if (!objDict)
    {
        [globalKeys setObject:[NSMutableDictionary dictionary] forKey:objKey];
    }
    [objDict setValue:value forKey:key];
}

Hope it helps.

Upvotes: 2

Related Questions