问题
I am getting an error when I try to add a new object to dataArray
. This is how I define dataArray
.
-(NSMutableArray *)dataArray{
if (!_dataArray){
_dataArray = [[NSMutableArray alloc] initWithObjects:
[NSMutableArray arrayWithObjects:
[NSMutableArray array],
[NSMutableArray array],
[NSMutableArray array],
nil],
[NSMutableArray arrayWithObjects:
[NSMutableArray array],
[NSMutableArray array],
[NSMutableArray array],
nil],
nil];
}
return _dataArray;
}
This is where I attempt to add an object to dataArray
:
[[[self.dataArray objectAtIndex:0] objectAtIndex:0] addObject:[NSString stringWithFormat:@"%@ %@",[attributeDict objectForKey:@"material"], [attributeDict objectForKey:@"tool"]]];
[[[self.dataArray objectAtIndex:0] objectAtIndex:1] addObject:[attributeDict objectForKey:@"level"]];
[[[self.dataArray objectAtIndex:0] objectAtIndex:2] addObject:[attributeDict objectForKey:@"probability"]];
Here is the error I am getting: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
Why am I getting this error and how can I fix it?
回答1:
Your argument to addObject:
is likely nil
.
Test it:
assert(attributeDict);
assert([attributeDict objectForKey:@"level"]);
assert([attributeDict objectForKey:@"probability"]);
回答2:
One of the values you're trying to insert is coming back nil
, which means attributeDict
does not contain either a "level" or "probability" key. The string should not be nil
even if it's provided with nil arguments, they just display as (nil)
.
回答3:
I fixed it. I misspelled a variable name.
来源:https://stackoverflow.com/questions/8797282/object-cannot-be-nil-error