Object cannot be nil error

喜欢而已 提交于 2019-12-02 23:54:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!