Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]);
}
like image 390
Anas Nakawa Avatar asked Dec 09 '22 14:12

Anas Nakawa


1 Answers

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.

like image 66
kennytm Avatar answered Dec 31 '22 19:12

kennytm