Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Objective-C property dynamically using the name of the property

I know the string name of a property of an object. How would I go about getting and setting that property using the string?

like image 403
quano Avatar asked Dec 28 '09 15:12

quano


People also ask

What is dynamic property in Objective-C?

@dynamic is for properties where you're not providing an implementation at compile time, but adding it later via Objective-C runtime magic. Since you're providing a setter here, that's clearly not the case, so...

What are Objective-C properties?

The Objective-C declared properties feature provides a simple way to declare and implement an object's accessor methods.


2 Answers

While @weichsel is correct, there is a better way.

Use:

[anObject valueForKey: @"propertyName"];

and

[anObject setValue:value forKey:@"propertyName"];

Obviously, @"propertyName" can be an NSString that is dynamically composed at runtime.

This technique is called Key Value Coding and is fundamental to Cocoa.

Why this is better is because -valueForKey will do what is necessary to "box" whatever type the property returns into an object. Thus, if the property is of type int, it'll return an NSNumber instance containing the int.

This is much easier to deal with -- performSelector will only work for types that happen to fit into a pointer's worth of memory.

Note that there is also -setValue:forKey:.

like image 136
bbum Avatar answered Oct 18 '22 20:10

bbum


@synthesize propertyName automates the generation of getter and setter methods.

The compiler generates

  • - (id)propertyName;
  • - (void)setPropertyName;

If you have a selector as NSString, you can use performSelector:NSSelectorFromString.
e.g.:
[object performSelector:NSSelectorFromString(@"propertyName") ...]

like image 43
Thomas Zoechling Avatar answered Oct 18 '22 20:10

Thomas Zoechling