KVC奇怪的行为(KVC strange behavior)

2019-07-28 06:01发布

为什么这个代码工作正常:

NSArray* arr = @[[CALayer layer], [CALayer layer]];
NSString *sumKeyPath = @"@sum.bounds.size.width";
CGFloat totalSize = [[arr valueForKeyPath:sumKeyPath] floatValue];

但是这个代码给错误:

NSArray* arr = @[[UIImage imageNamed:@"img1"], [UIImage imageNamed:@"img2"]];
NSString *sumKeyPath = @"@sum.size.width";
CGFloat totalSize = [[arr valueForKeyPath:sumKeyPath] floatValue];

错误 :[NSConcreteValue valueForUndefinedKey:]:这个类不是密钥值编码兼容的键宽度。

NSArray* arr = @[[UIView new], [UIView new]];
NSString *sumKeyPath = @"@sum.bounds.size.width";
CGFloat totalSize = [[arr valueForKeyPath:sumKeyPath] floatValue];

给予同样的错误

Answer 1:

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含有对象NSRectNSSize 键值兼容。 它只能与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"];

不工作。



Answer 2:

我认为错误告诉你正是这样的问题是什么! “这类不是密钥值编码兼容的键宽度”。



文章来源: KVC strange behavior