views:

456

answers:

1

Hiya,

When I started iPhone development, I read somewhere that it's possible to attach a key value pair to a UIView. I understood that all UIViews could be used as dictionaries to store any data you may want to attatch to them to prevent unnecessary subclassing. However, I've searched everywhere to find the reference and tried to implement the behavior myself in vain.

I've tried things such as:

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

but this doesn't seem to work. I think what the above code does is tried to assign the value @"hello" to the property @"world" - which isn't what I want.

Is what I'm trying to achieve possible?

Any help here would be much appreciated.

Thanks!

Nick.

+6  A: 

UIViews are not key-value compliant on generic keys. If they were, then your code sample would indeed set the value @"hello" for the key @"world". However, layers are key-value compliant, so the following would work:

UIView *myView = [[UIView alloc] init];
[myView.layer setValue: @"hello" forKey: @"world"];
Ben Gottlieb
You're a genius.Thanks so much for your help here Ben!
Nick Cartwright