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 isid), so you get an NSNumber or NSValue (I’m not sure which; it depends on whether theintValuegives an int or NSNumber, and (if the former) how the result is bundled back into an object), despite theintValue. It’s the same reason you can’t store non-objects in collections.