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?
Asked
Active
Viewed 2,345 times
2
-
3Try answering his question insetad of downvoting. – Jan 22 '12 at 00:16
3 Answers
7
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"];
3
Attach an NSMutableDictionary
to the UIView
using objc_setAssociatedObject
.

rob mayoff
- 375,296
- 67
- 796
- 848
-
-
working doesn't mean you can use it. Headers and libs are available but their use is prohibited. – Jan 22 '12 at 17:22
-
-
BTW Apple's [Recipes and Printing](http://developer.apple.com/library/ios/#samplecode/Recipes_+_Printing/Listings/Classes_RecipePrintPageRenderer_m.html) sample code uses `objc_setAssociatedObject`. – rob mayoff Jan 22 '12 at 17:27
-
1Of course you can use the Obj-C runtime functions! I have multiple apps in app store that use this. You just have to import the runtime header: #import
– Adam Nov 04 '12 at 17:13
2
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.
-
Thanks. I was thinking of something like this if there wasn't a way to actuall add the properties to the view itself. – Roger Jan 22 '12 at 17:13