为什么在检查 NSManagedObject 布尔属性后没有输入此 IF 块?

发布于 2024-10-28 06:08:49 字数 373 浏览 5 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

忆梦 2024-11-04 06:08:49

永远不会进入条件块的原因是 -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:.

岁吢 2024-11-04 06:08:49

这应该可以工作

if (![[eventToArchive valueForKey:@"archived"] boolValue])

boolValue 适用于 NSStringNSNumber ,因此如果 eventToArchive 的存档属性是 BOOL,键值编码会自动将其转换为 NSNumber< /代码> 给你。

This should work

if (![[eventToArchive valueForKey:@"archived"] boolValue])

boolValue works on NSStrings and NSNumbers so if the archived property of eventToArchive is a BOOL, Key Value Coding will automatically convert that into a NSNumber for you.

非要怀念 2024-11-04 06:08:49

假设“archived”是您需要执行的 NSManagedObject 子类的布尔属性;

if(![eventToAcrhive.archived boolValue]) {
    // not archived
}

Assuming that 'archived' is a boolean property on a subclass of NSManagedObject you need to do;

if(![eventToAcrhive.archived boolValue]) {
    // not archived
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文