Search code examples
objective-carrayscocoa-touchnsarrayboolean

NSArray and bool values


Can an NSArray hold an array of bool values?

The following code runs

BOOL b = NO;
NSMutableArray *array = [[NSMutableArray alloc] init];

[array addObject:[NSNumber numberWithBool:b]];

NSLog(@"value is %d", [array objectAtIndex:0] );

However, I don't get a value of 0 for NO as expected. Instead, this is what I get

value is 37736096


Solution

  • Yes, just wrap the booleans in NSNumber:

    BOOL b = YES;
    
    [array addObject:[NSNumber numberWithBool:b]];
    

    If you want to retrieve the boolean values, use this:

    BOOL b = [[array objectAtIndex:i] boolValue]; 
    // only if you know for sure it contains a boolean