Objective-C dictionary inserting a BOOL

前端 未结 6 702
说谎
说谎 2020-12-13 06:01

OK, I\'m a little confused. It\'s probably just a triviality.

I\'ve got a function which looks something like this:

- (void)getNumbersForNews:(BOOL)         


        
相关标签:
6条回答
  • 2020-12-13 06:03

    A BOOL is not an object - it's a synonym for an int and has 0 or 1 as its values. As a result, it's not going to be put in an object-containing structure.

    You can use NSNumber to create an object wrapper for any of the integer types; there's a constructor [NSNumber numberWithBool:] that you can invoke to get an object, and then use that. Similarly, you can use that to get the object back again: [obj boolValue].

    0 讨论(0)
  • 2020-12-13 06:06

    Modern code for reference:

    parameters[@"getNews"] = @(news);
    
    0 讨论(0)
  • 2020-12-13 06:12

    Seeing @Steve Harrison's answer I do have one comment. For some reason this doesn't work with passing object properties like for e.g.

     [parameters setValue:[NSNumber numberWithBool:myObject.hasNews] forKey:@"news"];
    

    This sets the news key to null in the parameter NSDictionary (for some reason can't really understand why)

    My only solution was to use @Eimantas's way as follows:

    [parameters setValue:[NSNumber numberWithBool:myObject.hasNews ? @"YES" : @"NO"] forKey:@"news"];
    

    This worked flawlessly. Don't ask me why passing the BOOL directly doesn't work but at least I found a solution. Any ideas?

    0 讨论(0)
  • 2020-12-13 06:20

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

    [parameters setValue:[NSNumber numberWithBool:news] forKey:@"news"];
    [parameters setValue:[NSNumber numberWithBool:mails] forKey:@"mails"];
    
    0 讨论(0)
  • 2020-12-13 06:21

    You can insert @"YES" or @"NO" string objects and Cocoa will cast it to bool once you read them back.

    Otherwise I'd suggest creating dictionary using factory method like dictionaryWithObjectsAndKeys:.

    0 讨论(0)
  • 2020-12-13 06:26

    Objective-C containers can store only Objective-C objects so you need to wrap you BOOL in some object. You can create a NSNumber object with [NSNumber numberWithBool] and store the result.
    Later you can get your boolean value back using NSNumber's -boolValue.

    0 讨论(0)
提交回复
热议问题