我创建了一个class:
@interface KVOGame : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *releaseDate;
@property (nonatomic, strong) KVOPlatform *platform;
@end
另一个是it属性:
@interface KVOPlatform : NSObject
@property (nonatomic, strong) NSString *platformName;
@property (nonatomic, strong) NSString *platformVersion;
@end
然后我尝试使用KVC获得"platformVersion",像这样
@interface KVOViewController ()
@end
@implementation KVOViewController
- (void)viewDidLoad
{
[super viewDidLoad];
KVOGame *game = [[KVOGame alloc] init];
game.name = @"Bayonetta";
game.releaseDate = @"8.10.2009";
game.platform.platformName = @"PS3, Xbox360";
game.platform.platformVersion = @"all versions";
NSString *identifier = @"platform.platformVersion";
NSLog(@"%@", [game valueForKey:identifier]);
}
并出现错误导致崩溃:
由于未捕获异常'NSUnknownKeyException'而终止应用程序,原因:'[valueForUndefinedKey:]:该类不符合key platform.platformVersion的键值编码'
我做错了什么?
更新:valueForKeyPath:
而不是valueForKey
也不工作-崩溃无论如何
try NSLog(@"%@", [game valueForKeyPath:identifier]);
我假设永远不会创建game.platform
。