How KVC Converts Strings to Numeric Types

Thanks to this discussion on Stack Overflow, I now understand how KVC is able to automatically convert string values to numeric types. As documented by Apple:

…setters like setValue:forKey: determine the data type required by a property’s accessor or instance variable, given a particular key. If the data type is not an object, the setter first sends an appropriate <type>Value message to the incoming value object to extract the underlying data, and stores that instead.

For example, if the type of the property being set is int:

@property int index;

KVC will attempt to invoke the intValue method on the provided value to convert it to the appropriate type before setting the property value:

[self setValue:@"10" forKey:@"index"]; // calls intValue on "10"

Thanks very much to Stack Overflow user CRD for providing the answer!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s