Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSArray filled with bool

Tags:

objective-c

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

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

this does not work for me.

Thanks

like image 618
Lilz Avatar asked Oct 08 '10 09:10

Lilz


2 Answers

NSArrays are not c-arrays. You cant access the values of an NSArray with array[foo];
But you can use c type arrays inside objective-C without 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, the now standard compiler for objective-c, understand Object subscripting. When you use a new version of clang you will be able to use array[0] = @YES

like image 71
Matthias Bauch Avatar answered Sep 18 '22 01:09

Matthias Bauch


Seems like you've confused c array with objc NSArray. NSArray is more like a list in Java, into which you can add objects, but not values like NSInteger, BOOL, double etc. If you wish to store such values in an NSArray, you first need to create a mutable array:

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

And then add proper object to it (in this case we'll use NSNumber to store your BOOL value):

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

And that's pretty much it! If you wish to access the bool value, just call:

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

Cheers, Pawel

like image 20
Pawel Avatar answered Sep 18 '22 01:09

Pawel