Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

objective c - KVC strange behavior

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

CALayer has a special implementation for valueForKeyPath:. For example, the following works:

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

But the following does not work:

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.'

So generally, NSValue objects containing a NSRect or NSSize are not key-value compliant. It works only with CALayer because the valueForKeyPath: 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 for valueForKeyPath:. Therefore

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

works, but

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

does not work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...