Objective c key path operators @avg,@max
arr = [[NSMutableArray alloc]init];
[开发者_开发问答arr addObject:[NSNumber numberWithInt:4]];
[arr addObject:[NSNumber numberWithInt:45]];
[arr addObject:[NSNumber numberWithInt:23]];
[arr addObject:[NSNumber numberWithInt:12]];
NSLog(@"The avg = %@", [arr valueForKeyPath:@"@avg.intValue"]);
This code works fine, but why? valueForKeyPath:@"@avg.intValue"
is requesting (int) from each NSNumber, but we are outputting a %@ string in the log. If i try to output a decimal %d i get a number that possibly is a pointer to something. Can somebody explain why the integers become NSNumbers when i call the @avg operator?
valueForKeyPath:
must return an object (its return type is id
), so you get an NSNumber or NSValue (I'm not sure which; it depends on whether the intValue
gives an int or NSNumber, and (if the former) how the result is bundled back into an object), despite the intValue
. It's the same reason you can't store non-objects in collections.
The @avg
operator returns an NSNumber
instance. If you use %d
, you will print the memory address of the NSNumber
instance. When you use %@
, on the other hand, the NSNumber
instance is sent a description
message, and the resulting NSString
is printed.
See Set and Array Operators in the Key-Value Coding Programming Guide for more information on @avg
and other operators.
精彩评论