attempt to insert nil object from objects[0]?

SimplyKiwi picture SimplyKiwi · Aug 13, 2012 · Viewed 50.4k times · Source

In my application I have a UITableView and some buttons that the user can click to sort the array to the order based upon some NSDate's or ints. So this is my method to try to sort my UITableView:

- (void)sortStats:(id)sender reloadData:(BOOL)dataBool {
    NSSortDescriptor *descriptor = nil;
    UIButton *clickedButton = (UIButton*)sender;
    if (clickedButton.tag == 1) {
            descriptor = [NSSortDescriptor sortDescriptorWithKey:@"Date" ascending:NO];
    }
    [self.cellArray sortUsingDescriptors:[NSArray arrayWithObject:descriptor]];
    [[NSUserDefaults standardUserDefaults] setObject:self.cellArray forKey:@"cellArray"];
    if (dataBool) {
        [ivstatstableView reloadData];
    }
    [ivstatstableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
}

So originally I just had this method without the reloadData parameter because it seemed that reloadData on the UITableView was causing the crash.

This is what the console crash log is:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[0]'

Anyway is there any code here that would be causing this crash? I really want to get this functionality working in my app and I know I am close to fixing it but I am just not sure whats causing this issue.

Any ideas?

Answer

Tim Dean picture Tim Dean · Aug 13, 2012

There is at least one place where this could be happening, and perhaps others. In the code where you get the contents of the user defaults, you don't check for nil. So instead of this:

[self.cellArray addObjectsFromArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"array"]];

you might want to try this:

NSArray *defaultCellArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"array"];
if (defaultCellArray) {
    [self.cellArray addObjectsFromArray:defaultCellArray];
}

It is also possible that the initWithObjects call that is failing (according to your error message) is nested within another call, perhaps in this call:

[self.cellArray sortUsingDescriptors:[NSArray arrayWithObject:descriptor]];

If you look at the full call stack it would tell you if this call is making subsequent calls to initWithObjects and possibly passing it a nil. In your case, for example, you would pass in a nil yo the array you are creating if clickedButton.tag has not yet been set to a value of 1 or 2. You might want to add an additional else clause to help diagnose the problem:

if (clickedButton.tag == 1) {
        descriptor = [NSSortDescriptor sortDescriptorWithKey:@"Date" ascending:NO];
} else if (clickedButton.tag == 2) {
        descriptor = [NSSortDescriptor sortDescriptorWithKey:@"Score" ascending:NO];
} else {
    NSLog(@"Unexpected error: Can't determine sort descriptor");
}