1

Possible Duplicate:
obj-c access property dynamically

I'm attempting to access an object’s properties dynamically using strings. I know that we can access classes dynamically etc but is this possible for properties? For example, instead of directly accessing the property name, can we use a NSString to access it?

@property (retain,nonatomic) int height;

NSString *stringName = @"height"; object.stringName = 30.0f;

where object.height == object.stringName;
Community
  • 1
  • 1
Ospho
  • 2,756
  • 5
  • 26
  • 39

1 Answers1

4

You can do this using KVC.

[[object valueForKey:@"height"] intValue]

All properties automatically opt into the KVC system.

Joshua Weinberg
  • 28,598
  • 2
  • 97
  • 90
  • Provided that your object is a child of NSObject.. correct? – Muhammad Hewedy Nov 15 '11 at 06:03
  • @Muhammad correct, but if your object isn't...you did something weird. – Joshua Weinberg Nov 15 '11 at 06:28
  • Thanks heaps. I'll give it a shot. Sorry but what is KVC? – Ospho Nov 15 '11 at 06:36
  • `Key-value coding is a mechanism for accessing an object’s properties indirectly, using strings to identify properties, rather than through invocation of an accessor method or accessing them directly through instance variables. In essence, key-value coding defines the patterns and method signatures that your application’s accessor methods implement.` From here: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueCoding/Articles/Overview.html#//apple_ref/doc/uid/20001838-SW1 – Muhammad Hewedy Nov 15 '11 at 11:00
  • Other hard-way solution is to use `performSelector`, but Joshua solutions is better if not the best. https://github.com/MuhammadHewedy/ObjectMapper/blob/master/ObjectMapper/ObjectMapper/ObjectMapper.m#L165 – Muhammad Hewedy Nov 15 '11 at 11:04