为什么在检查 NSManagedObject 布尔属性后没有输入此 IF 块?
NSLog(@"move report - %@", [eventToArchive valueForKey:@"archived"]);
if (![eventToArchive valueForKey:@"archived"]) {
....
上面的代码块永远不会被输入,即使 NSLog
move report - 0
每次运行时都会返回?
我需要做类似的事情吗
if (![NSNumber numberWithBool:[eventToArchive valueForKey:@"archived"]]) {
?
NSLog(@"move report - %@", [eventToArchive valueForKey:@"archived"]);
if (![eventToArchive valueForKey:@"archived"]) {
....
The above code block is NEVER being entered, even though NSLog returns
move report - 0
Every single time it runs?
Do I need to do something like,
if (![NSNumber numberWithBool:[eventToArchive valueForKey:@"archived"]]) {
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
永远不会进入条件块的原因是 -valueForKey: 返回一个
id
,即一个指针。然而,您将它当作一个 BOOL 来使用,因此您进入该块的唯一方法是 if -valueForKey: returns nil。您的日志语句打印“0”作为值,因为您使用了对象格式说明符
%@
,它需要一个指针并打印该指针指向的对象的描述。您可能给它一个 NSNumber*,并且它正确地打印了该对象表示的值。前面的两个答案正确地指出您应该使用 -boolValue 方法从 -valueForKey: 获得的 NSNumber 中获取 BOOL 值。
The reason that the conditional block is never entered is that -valueForKey: returns an
id
, which is to say a pointer. You're using it as though it were a BOOL, however, so the only way you'll ever enter that block is if -valueForKey: returns nil.Your log statement prints "0" as the value because you used the object format specifier,
%@
, which expects a pointer and prints a description of the object that the pointer points to. You're probably giving it a NSNumber*, and it's properly printing the value represented by that object.The preceding two answers are correct in pointing out that you should use the -boolValue method to get a BOOL value from the NSNumber that you get from -valueForKey:.
这应该可以工作
boolValue 适用于
NSString
和NSNumber
,因此如果 eventToArchive 的存档属性是 BOOL,键值编码会自动将其转换为NSNumber< /代码> 给你。
This should work
boolValue works on
NSString
s andNSNumber
s so if the archived property of eventToArchive is a BOOL, Key Value Coding will automatically convert that into aNSNumber
for you.假设“archived”是您需要执行的 NSManagedObject 子类的布尔属性;
Assuming that 'archived' is a boolean property on a subclass of NSManagedObject you need to do;