2

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

4

2 回答 2

8

CALayer有一个特殊的实现valueForKeyPath:。例如,以下工作:

CALayer *layer = [CALayer layer];
id x0 = [layer valueForKeyPath:@"bounds"];
// --> NSValue object containing a NSRect
id y0 = [layer valueForKeyPath:@"bounds.size"];
// --> NSValue object containing a NSSize
id z0 = [layer valueForKeyPath:@"bounds.size.width"];
// --> NSNumber object containing a float

但以下不起作用:

CALayer *layer = [CALayer layer];
id x = [layer valueForKey:@"bounds"];
// --> NSValue object containing a NSRect
id y = [x valueForKey:@"size"];
// --> Exception: '[<NSConcreteValue 0x71189e0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key size.'

所以一般来说,NSValue包含NSRectorNSSize的对象符合键值。它仅适用于CALayer因为valueForKeyPath:实现处理整个密钥路径,而不是评估第一个密钥并传递剩余的密钥路径。

UIImage没有特殊的实现valueForKeyPath:。所以

UIImage *img1 = [UIImage imageNamed:@"img1"];
id x1 = [img1 valueForKey:@"size"];
// --> NSValue containing a NSSize

有效,但是

UIImage *img1 = [UIImage imageNamed:@"img1"];
id x1 = [img1 valueForKeyPath:@"size.width"];

不起作用。

于 2013-03-27T11:41:00.243 回答
2

我认为该错误可以准确地告诉您该问题是什么!“这个类不符合键宽的键值编码。”

于 2013-03-27T11:06:06.237 回答