Object cannot be nil error

2020-05-10 08:55发布

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?

3条回答
聊天终结者
2楼-- · 2020-05-10 09:41

I fixed it. I misspelled a variable name.

查看更多
可以哭但决不认输i
3楼-- · 2020-05-10 09:49

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).

查看更多
▲ chillily
4楼-- · 2020-05-10 09:52

Your argument to addObject: is likely nil.

Test it:

assert(attributeDict);
assert([attributeDict objectForKey:@"level"]);
assert([attributeDict objectForKey:@"probability"]);
查看更多
登录 后发表回答