Anthony McCormick
Anthony McCormick

Reputation: 2744

Dynamic object properties in Objective-c

How do i create dynamic properties on an object in objective-c? in ActionScript we can do something like this

var obj : Object;
obj[ "myDynamicProperty" ] = true;
trace( obj.myDynamicProperty );

How would i do this in objective-c?

I have tried the following

NSObject *obj = [[NSObject alloc] init];
[obj setValue:@"labelValue" forKey:@"label"];

But that just throws a runtime error. Any help would be much appreciated. Thanks in advance.

Upvotes: 0

Views: 2194

Answers (3)

Jason Foreman
Jason Foreman

Reputation: 2146

Objects-NSObjects, to be specific-in Objective-C do not allow arbitrary properties to be set on them using KVC; that is, they are not key-value containers. If you want something that can accept arbitrary key-value pairs, use a dictionary (NSMutableDictionary).

You could also use the associated objects API if you are comfortable enough dropping down to the Obj-C runtime. Search for objc_setAssociatedObject in the documentation to see how you can use this API.

Upvotes: 10

Chuck
Chuck

Reputation: 237110

Objects in Objective-C don't normally work this way. It is possible with runtime functions, but resorting to runtime functions is awkward and generally not idiomatic. If you want an arbitrary key-value store, use NSMutableDictionary.

In general, it's good practice in Objective-C so that every object has a fixed set of properties instead of tacking them on ad hoc like we sometimes do in ActionScript/Javascript.

Upvotes: 0

andyvn22
andyvn22

Reputation: 14824

If you need custom behavior in addition to arbitrary properties, you can create a decorator object. Make your own custom class that contains an NSMutableDictionary instance variable, then write your own methods that simply call setValue:forKey: and so forth on that internal dictionary.

Upvotes: 3

Related Questions