Anas Nakawa
Anas Nakawa

Reputation: 2015

How to deal with booleans in NSMutableArrays?

Can someone tell me why my application crashes here ?

and why it does not crash when i replace the YES objects with NSString values ?

all i want to do is to store boolean data into array and to modify these data later, can someone please tell me how to do this ?

- (void)viewDidLoad {
    [super viewDidLoad];
    NSMutableArray* arr = [[NSMutableArray alloc] initWithObjects:YES, YES, YES, YES, nil];
    NSLog([arr objectAtIndex:1]);
}

Upvotes: 4

Views: 4087

Answers (1)

kennytm
kennytm

Reputation: 523214

YES and NO are BOOLs, which is not an Objective-C class. Foundation containers can only store Objective-C objects.

You need to wrap them in an NSNumber, like:

NSNumber* yesObj = [NSNumber numberWithBool:YES];
NSMutableArray* arr = [[NSMutableArray alloc] initWithObjects:
                                               yesObj, yesObj, yesObj, yesObj, nil];
NSLog(@"%d", [[arr objectAtIndex:1] boolValue]);

The reason why it accepts NSString is because an NSString is a kind of Objective-C class.

Upvotes: 14

Related Questions