Search code examples
iosobjective-cnsmanagedobjectnsmanagedobjectcontextnsfetchrequest

iOS: Problem with the NSManagedObjectContext / NSFetchRequest / NSEntityDescription


I have an error message ' Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: ' -[__NSArrayM insertObject:atIndex:]: object cannot be nil'

The problem is on the fetchedObjects.

This is because it tries to add a value that is nil to an NSArray. What I don't understand, is why there is that empty value.

For info: The table is the name of the table of my sqlite and the label is just a field of my table.

- (NSMutableArray*) getLabel:(NSString *)label fromTable:(NSString *)table 
{
    NSMutableArray * ret = [NSMutableArray new];
    NSError *error = nil;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:table
                                              inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];
    NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

    Class theClass = NSClassFromString(table);
    id info = [[theClass alloc] initWithEntity:entity insertIntoManagedObjectContext:managedObjectContext];

    for (info in fetchedObjects)
    {
        [ret addObject:[info valueForKey: label]];
    }
    return ret;
}

Good initialization:
enter image description here

Bad initialization:
enter image description here

Do you have any ideas? Thanks in advance.


Solution

  • It is a common error. I think you should have a look at your line:

    id info = [[theClass alloc] initWithEntity:entity insertIntoManagedObjectContext:managedObjectContext];
    

    Look here if you want to have more info: Use NSManagedObject class without initWithEntity:?

    You should insertIntoManagedObjectContect:nil