Objective-C dictionary inserting a BOOL

Posted in :

把  BOOL 放進 NSDictionary 會出錯,必需是要 NS系列的物件才能進戈。

解法1:

Values in an NSDictionary must be objects. To solve this problem, wrap the booleans in NSNumberobjects:

[parameters setValue:[NSNumber numberWithBool:news] forKey:@"news"];
[parameters setValue:[NSNumber numberWithBool:mails] forKey:@"mails"];

 

BOOL can be wrapped in an NSNumber object:

dicTemp[@"is_default"] = @YES;

(This code is using the newish Objective-C Literals syntax).

If you are old-fashioned (nothing wrong with that), then the above statement is the same as:

[dicTemp setObject:[NSNumber numberWithBool:YES]
            forKey:@"is_default"];

To test later:

NSNumber *numObj = dicTemp[@"is_default"];
if ([numObj boolValue]) {
    // it was YES
}

解法2:

The new syntax since Apple LLVM Compiler 4.0

dictionary[@"key1"] = @(boolValue);
dictionary[@"key2"] = @YES;

The syntax converts BOOL to NSNumber, which is acceptable to NSDictionary.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *