Attempt to insert nil
Seems like it should be easy to add a boolean to an NSMutableArray.
Assume toDoArray is intialized as an NSMutable开发者_StackOverflow中文版Array. 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?
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.
NSMutable arrays require an id, a weird part of Objective C. An id is any object, but not a primitive (For example, int
s are primitives, while NSArray
s are objects, and in extension, id
s).
This question might help.
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];
精彩评论