views:

409

answers:

3

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?

+3  A: 

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.

Jeffrey Aylesworth
Nothing weird about `id`. Objective-C doesn't have a fixed root class and, thus, `id` exists as a reference to an instance of any class.
bbum
I guess it's just me that finds it weird then.
Jeffrey Aylesworth
+5  A: 

Looks like

[NSNumber numberWithBool:NO]

Will be the way to go here. Thanks!

iconmaster
If you have an answer that you like, accept the answer. (StackOverflow isn't a forum)
bbum
+5  A: 

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.

bbum