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开发者_StackOverflow中文版 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.
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
.
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.
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.
精彩评论