我正在学习目标-c。我按照一本书编写了下面的代码来测试NSObject的键值观察器。
@implementation BNRObserver
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
//ERROR: implicit conversion of 'NSUInteger' to 'id' is disallowed with ARC
NSString *oldValue = [change objectForKey:NSKeyValueObservingOptionOld];
NSString *newValue = [change objectForKey:NSKeyValueObservingOptionNew];
NSLog(@"Observed: %@ of %@ was changed from %@ to %@",
keyPath, object, oldValue, newValue);
}
@end
但是objectForKeyI
抱怨:
implicit conversion of 'NSUInteger' to 'id' is disallowed with ARC
为什么我收到此错误?如何解决?
P.S。上面的代码来自本书:Objective-C Programming The Big Nerd Ranch Guide 2nd Edition。
答案 0 :(得分:1)
您使用的是错误的密钥。您使用的值是观察选项。您在NSKeyValueChangeOldKey
和NSKeyValueChangeNewKey
之后。
即:
NSString *oldValue = [change objectForKey:NSKeyValueChangeOldKey];
NSString *newValue = [change objectForKey:NSKeyValueChangeNewKey];
答案 1 :(得分:0)
如果仔细查看错误消息,您将无法将其从NSUInteger(数字)类型转换为id(任何对象)。如果您查看定义(按住命令键并单击NSKeyValueObservingOptionOld),您将看到以下内容:
NSKeyValueObservingOptionOld = 0x02
但是NSDictionary只允许键的对象,而不是数字。
=>解决方案:将NSKeyValueChangeOldKey / NSKeyValueChangeNewKey作为键,NSString类型
NSString *oldValue = (NSString *)change[NSKeyValueChangeOldKey];
NSString *newValue = (NSString *)change[NSKeyValueChangeNewKey];
使用现代的obj-c,你甚至不必使用objectForKey:-method
如果您希望查看字典的所有内容,请执行:
NSLog(@"%@", change);