NSArray filled bool

I am trying to create an NSArray of bool values. How much do I do this, please?

NSArray *array = [[NSArray alloc] init]; array[0] = YES; 

this does not work for me.

thanks

+5
objective-c
source share
3 answers

NSArrays are not c-arrays. You cannot access NSArray values ​​with array[foo];
But you can use arrays of type c inside objective-C without any problems.

The objective-C approach would be:

 NSMutableArray *array = [[NSMutableArray alloc] init]; [array addObject:[NSNumber numberWithBool:YES]]; //or [array addObject:@(NO)]; ... BOOL b = [[array objectAtIndex:0] boolValue]; .... [array release]; 

EDIT: new versions of clang, now the standard compiler for objective-c, understand subscribing to objects . When you use the new version of clang, you can use array[0] = @YES

+13
source share

It looks like you messed up the c array with objc NSArray. NSArray is more like a list in Java, in which you can add objects, but not values ​​like NSInteger, BOOL, double, etc. If you want to store such values ​​in NSArray, you first need to create a mutable array:

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

And then add the appropriate object to it (in this case we will use NSNumber to store your BOOL value):

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

And that is pretty much! If you want to access the bool value, just call:

 BOOL yourBoolValue = [[array objectAtIndex:0] boolValue]; 

Cheers, Pawel

+3
source share

Use [NSNumber numberWithBool: YES] to get an object that you can put in a collection.

+2
source share

All Articles