为bool分配值而不给出预期结果

时间:2014-05-13 19:40:17

标签: objective-c boolean

以下代码:

usepassive = [agencydata valueForKey:@"passive"];
                NSLog(@"agencydata usepassive: %@",[agencydata valueForKey:@"passive"]);
                NSLog(@"vardata usepassive: %hhd",usepassive);

生成此输出:

2014-05-13 21:35:41.424 Stockuploader[957:303] agencydata usepassive: 1
2014-05-13 21:35:41.425 Stockuploader[957:303] vardata usepassive: 7

我希望它是1和1,但它是1和7.

usepassive在我的.h文件中声明为此BOOL usepassive;

出了什么问题?

1 个答案:

答案 0 :(得分:4)

您无法将BOOL个对象存储在字典(或其他集合)中,而无需先将其包装在NSNumber中。这意味着当您从字典中获取值时,您将获得NSNumber。您需要将其转换为BOOL

你可以这样做:

// Assuming usepasive is defined as BOOL
usepassive = [[agencydata objectForKey:@"passive"] boolValue];
NSLog(@"agencydata usepassive: %@", [agencydata objectForKey:@"passive"]); // logs the NSNumber
NSLog(@"vardata usepassive: %hhd", usepassive); // logs the BOOL

还要考虑现代语法:

usepassive = [agencydata[@"passive"] boolValue];
NSLog(@"agencydata usepassive: %@", agencydata[@"passive"]); // logs the NSNumber
NSLog(@"vardata usepassive: %hhd", usepassive); // logs the BOOL