Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 651
node ninja Avatar asked Sep 22 '10 13:09

node ninja


2 Answers

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
like image 120
Philippe Leybaert Avatar answered Sep 23 '22 08:09

Philippe Leybaert


To complete Philippe answer, you should make usage of litteral string introduced in XCode 4.4 with the release of Apple LLVM Compiler version 4.0.

Your code will look like this:

NSMutableArray *array = [[NSMutableArray alloc] init];

array[0] = @YES;

//Value is 1
NSLog(@"Value is %d:", [array[0]  boolValue]);
like image 25
tiguero Avatar answered Sep 24 '22 08:09

tiguero