tags:

views:

31

answers:

3

Hi

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

+1  A: 

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

Graham Lee
array[0] = [NSNumber numberWithBool: YES]; gives me an 'incompatible types in assignment' error
Lily
[array addObject:[NSNumber numberWithBool:YES]]
William Remacle
+3  A: 

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]];
...
BOOL b = [[array objectAtIndex:0] boolValue];
....
[array release];
fluchtpunkt
I'm trying that and its giving me *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[NSNumber numberWithBOOL:]: unrecognized selector sent to class
Lily
should be [NSNumber numberWithBool:YES]. Sorry, my mistake
fluchtpunkt
oh thanks a lot!
Lily
+2  A: 

Hello Lilly,

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

Pawel