Say I have the following Objective-C class:
@interface Foo { int someNumber; NSString *someString; }
and for reasons I won’t get into here, I want to use KVC to update, in a generic fashion, the values for those variables:
[f setValue:object forKey:@'someNumber']; or [f setValue:object forKey:@'someString'];`
If object is a string and I’m updating the someNumber variable, it seems that I need to know to use an NSNumberFormatter to get an NSNumber and then Cocoa automatically converts that to an int inside setValue:forKey:.
Is there any way to avoid this custom code and have Cocoa infer the conversion to an int from a string, or do I need to catch this situation each time and handle it myself?
You should do the conversion yourself with a number formatter, it gives you finer control than anything that the framework might consider to be appropriate. It is also, probably, not a good idea to use a single instance of an object to update the values for your ivars. More appropriately, you could perform your update based on the class of the object (providing you are not storing in an
idby querying the runtime as to the class of the object by means ofobject_getClassName. More information is available in the Objective-C 2.0 Runtime Reference. But in general, you will likely find bugs in your code as a result of doing things that way.