There’s the option to go the long way, if an receiver class conforms to the NSKeyValueProtocol:
[myInstance setValue:[NSNumber numberWithInt:2] forKey:@"integerProperty"];
or the short way:
myInstance.integerProperty = 2;
what’s the point of this KVC method? When is this useful?
First, those aren’t the same, the second should be:
if
integerPropertyis anNSNumber.In general you use the second form when you are doing the most things. You use
setValue:forKey:andvalueForKey:when you want to dynamically choose the property to store things in. For instance, think about howvalueForKeyPath:against anNSArrayworks (for reference, if you call-valueForKey:against anNSArrayit will return an array where each object is the result of asking the corresponding object in thatNSArrayfor that value:In the above case we were able to use
valueForKey:to implement our function even though we do not know what the key is beforehand, since it is passed in as an argument.