Why this code works fine:
NSArray* arr = @[[CALayer layer], [CALayer layer]];
NSString *sumKeyPath = @"@sum.bounds.size.width";
CGFloat totalSize = [[arr valueForKeyPath:sumKeyPath] floatValue];
But this code give error:
NSArray* arr = @[[UIImage imageNamed:@"img1"], [UIImage imageNamed:@"img2"]];
NSString *sumKeyPath = @"@sum.size.width";
CGFloat totalSize = [[arr valueForKeyPath:sumKeyPath] floatValue];
Error: [NSConcreteValue valueForUndefinedKey:]: this class is not key value coding-compliant for the key width.
NSArray* arr = @[[UIView new], [UIView new]];
NSString *sumKeyPath = @"@sum.bounds.size.width";
CGFloat totalSize = [[arr valueForKeyPath:sumKeyPath] floatValue];
give the same error
I think the error tells you exactly what that problem is! "this class is not key value coding-compliant for the key width."
CALayer
has a special implementation forvalueForKeyPath:
. For example, the following works:But the following does not work:
So generally,
NSValue
objects containing aNSRect
orNSSize
are not key-value compliant. It works only withCALayer
because thevalueForKeyPath:
implementation handles the entire key path, instead of evaluating the first key and passing down the remaining key path.UIImage
does not have a special implementation forvalueForKeyPath:
. Thereforeworks, but
does not work.