2

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?

Roger
  • 753
  • 8
  • 12

3 Answers3

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"];
Community
  • 1
  • 1
ftvs
  • 428
  • 1
  • 6
  • 14
3

Attach an NSMutableDictionary to the UIView using objc_setAssociatedObject.

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

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • on iOS, one can't use the Objective-C runtime functions directly. –  Jan 22 '12 at 17:14
  • working doesn't mean you can use it. Headers and libs are available but their use is prohibited. –  Jan 22 '12 at 17:22
  • Link to any documentation of this claim? – rob mayoff 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
  • 1
    Of 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