8

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.

Chris Hanson
  • 54,380
  • 8
  • 73
  • 102
Nick Cartwright
  • 8,334
  • 15
  • 45
  • 56

1 Answers1

25

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
  • 85,404
  • 22
  • 176
  • 172
  • You're a genius. Thanks so much for your help here Ben! – Nick Cartwright Dec 30 '08 at 13:41
  • 1
    If you're not sure what the difference is between a UIView and a layer is (like me until 10 minutes ago), check out http://raptureinvenice.com/ios-brownbag-view-vs-layers-including-clock-demo/ – Joseph Aug 21 '12 at 20:10