Question

Seems like it should be easy to add a boolean to an NSMutableArray.

Assume toDoArray is intialized as an NSMutableArray. The following:

BOOL checkBoxState = NO;
[toDoArray addObject:checkBoxState]; 

Generates the error "attempt to insert nil."

What's the correct way to add a negative boolean to a mutable array?

Was it helpful?

Solution

NSMutable arrays require an id, a weird part of Objective C. An id is any object, but not a primitive (For example, ints are primitives, while NSArrays are objects, and in extension, ids).

This question might help.

OTHER TIPS

As others have said, NSMutableArray can only contain Objective-C objects. They do not have to be subclasses of NSObject, but that is the most typical.

However, long before you ever see the attempt to insert nil. runtime error, you should have seen a compiler warning:

warning: passing argument 1 of 'addObject:' makes pointer from integer without a cast

It is [in a vague and roundabout way] telling you exactly what the problem is; you are trying to stick something into an array that is not a pointer [to an object].

Pay attention to warnings and fix them. Most of the time, the presence of a warning will indicate a runtime error or crash.

You need using NSNumber to wrap any primitive types (BOOL, int, NSInterger, etc.) before placing it inside collection object (NSArray, NSDictionary, etc.).

Add BOOL to array:

BOOL checkBoxState = NO;
NSNumber* n = [NSNumber numberWithBool:checkBoxState];
[toDoArray addObject:n];

Get BOOL from array:

NSNumber* n = [toDoArray objectAtIndex:0];
BOOL checkBoxState = [n boolValue];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top