我创建了类:
@interface KVOGame : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *releaseDate;
@property (nonatomic, strong) KVOPlatform *platform;
@end
另一个属性:
@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:]:此类不是密钥platform.platformVersion的密钥值编码兼容。'
我做错了什么?
更新:valueForKeyPath:
而不是valueForKey
也无效 - 无论如何都会崩溃。
答案 0 :(得分:3)
尝试NSLog(@"%@", [game valueForKeyPath:identifier]);
我认为永远不会创建game.platform
。这是零