How do I generally use KVC to update fields?

Say I have the following Objective-C class:

@interface Foo {
     int someNumber;
     NSString *someString;
}

and for reasons that I will not participate here, I want to use KVC to update in general terms the values ​​for these variables:

[f setValue:object forKey:@"someNumber"];

or

[f setValue:object forKey:@"someString"];`

If it objectis a string and I am updating the variable someNumber, it seems to me that I need to know how to use NSNumberFormatter to get the NSNumber, and then Cocoa will automatically convert this to int inside setValue:forKey:.

Is there a way to avoid this custom code and have Cocoa output the conversion to int from a string, or do I need to check this situation each time and handle it myself?

+3
source share
3 answers

, , , . , , . , ( , id object_getClassName. Objective-C 2.0 Runtime Reference. , , , .

+1

, object , integerValue.

, NSNumber NSString .

- (void)setValue:(id)object forKey:(NSString *)key
{
    if ([key isEqual:@"someNumber"])
    {
        someNumber = [object integerValue];
    }
    //...
}

: ( ): , objective-c. setValue:forKey: , someNumber someString.

+2

. setValue: forKey: setter . :

- (void)setSomeValue:(NSInteger)aValue

, NSString , .

, , . KVC NSNumber, setValue: forKey:. , , NSNumber.

In such cases, I complain that Cocoa Touch does not support bindings. Bindings allow you to add a value converter that can handle the conversion from string to number automatically for you. Perhaps in the next version!

+1
source

All Articles