Core Data Crash: [__NSArrayM insertObject:atIndex:]: object cannot be nil

14,857

Solution 1

I had a similar problem with the same error message when my code ran [NSManagedObjectModel mergedModelFromBundles:nil]. This happened after xCode crashed on me unexpectedly. Even when I reverted back to a known good version of my code, I still had the same error that was due to some sort of corruption.

After much experimenting, I was able to solve the problem by exiting Xcode and the iPhone simulator, and then deleting all files from the following directories:

$ cd /Users/john/Library/Developer/Xcode/DerivedData

$ rm -R -f ./(folder corresponding to my project name)

$ cd /Users/john/Library/Application Support/iPhone Simulator/5.0/Applications

$ rm -R *

This was able to clear the corrupted temporary files and state for the simulator, and the error disappeared.

Solution 2

I moved my Model.xcdatamodeld file to another folder, and got this error. Starting with a clean emulator didn't help. Apparently Xcode keeps a reference to this file somewhere.

My fix was to backup my old Model.xcdatamodeld file, remove it from the project, create a new model file in the same folder and then replace this file with the backup.

Solution 3

Had a similar error. When you first create the model in Xcode, it seems to store the name of the model internally.

I renamed the model file - this caused the problem mentioned by OP.

Reverting the model name back (and doing a build clean + deleting the app form the device) fixed the issue for me.

Solution 4

There's a lot of answers here, but I'm not sure any of them concisely state exactly what is wrong.

My understanding is that the root cause of this crash is that your app, when installed on the device, has a model that is empty. eg. if you look on the device with iFunBox/iExplore, you see a MyApp.app/MyModel.momd that has a VersionInfo.plist where the NSManagedObjectModel_VersionHashes dictionary is empty, or the NSManagedObjectModel_CurrentVersionName points at a model that doesn't exist.

The reasons for that can vary, but basically all relate back to your model not being setup properly in xcode. In our case the project file had got out of sync with the filesystem and the model was in a different location to where xcode though it was, but having an empty latest version could also cause it. Most of these can be fixed by removing the project from xcode and adding it again, then checking the latest version is correctly set.

With problems of this nature, it's also pretty important to test from a clean state - ie. cleaning the build folder in xcode (cmd-shift-option k) and deleting the app from the device/simulator (as otherwise xcode can leave files lying around that make it look like things are working).

There appears to be a bug in xcode (at least in xcode 4.6 and 5.0.1) that means it doesn't issue a build warning in some of these cases when it should be able to. I've raised that in Apple's bugreporter as 15186008.

Solution 5

I had exactly the same error after I renamed the core data model file. Deleting Xcode/DerivedData directory, cleaning project, uninstalling app from simulator, restarting Xcode, upgrading Xcode, etc. did not work.

In order to get it to work again, I have selected "iOS Simulator" -> "Reset Content and Settings..." from the top menu.

Share:
14,857
saimonx
Author by

saimonx

iOs Developer

Updated on June 14, 2022

Comments

  • saimonx
    saimonx almost 2 years

    I am trying to implement CoreData in my application to store a small database.

    Here my implementation:

    AppDelegate.h

    #import <UIKit/UIKit.h>
    #import "FavoritosViewController.h"
    #import <CoreData/CoreData.h>
    
    @interface XXX : NSObject <UIApplicationDelegate>{
    
        NSManagedObjectModel *managedObjectModel;
        NSManagedObjectContext *managedObjectContext;       
        NSPersistentStoreCoordinator *persistentStoreCoordinator;
    
    
    
    }
    - (NSString *)applicationDocumentsDirectory;
    
    @property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
    @property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
    @property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
    
    @end
    

    AppDelegate.m

        - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
        FavoritosViewController *global=[[FavoritosViewController alloc]init];
    
        global.managedObjectContext=[self managedObjectContext];
    
        .
        .
        .
        }
    
            - (void)applicationWillTerminate:(UIApplication *)application
        {
            NSError *error = nil;
            if (managedObjectContext != nil) {
                if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
                    /*
                     Replace this implementation with code to handle the error appropriately.
    
                     abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
                     */
                    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
                    abort();
                } 
            }
    
        }
    
    - (NSManagedObjectContext *) managedObjectContext {
    
        if (managedObjectContext != nil) {
            return managedObjectContext;
        }
    
        NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
        if (coordinator != nil) {
            managedObjectContext = [[NSManagedObjectContext alloc] init];
            [managedObjectContext setPersistentStoreCoordinator: coordinator];
        }
        return managedObjectContext;
    }
    
    
    /**
     Returns the managed object model for the application.
     If the model doesn't already exist, it is created by merging all of the models found in the application bundle.
     */
    - (NSManagedObjectModel *)managedObjectModel {
    
        if (managedObjectModel != nil) {
            return managedObjectModel;
        }
        managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];    
        return managedObjectModel;
    }
    
    
    /**
     Returns the persistent store coordinator for the application.
     If the coordinator doesn't already exist, it is created and the application's store added to it.
     */
    - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    
        if (persistentStoreCoordinator != nil) {
            return persistentStoreCoordinator;
        }
    
        NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"FavoritosDatabase.sqlite"]];
    
        NSError *error = nil;
        persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
        if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
            /*
             Replace this implementation with code to handle the error appropriately.
    
             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
    
             Typical reasons for an error here include:
             * The persistent store is not accessible
             * The schema for the persistent store is incompatible with current managed object model
             Check the error message to determine what the actual problem was.
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }    
    
        return persistentStoreCoordinator;
    }
    
    
    
    
    - (NSString *)applicationDocumentsDirectory {
        return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    }
    

    I have also a xcdatamodeld with "Event" entity with theirs attributes, and Event.h, Event.m from it.

    In FavoritosViewController I have also all the methods, but the problem comes before all that.

    It comes at

    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];    
    

    The app crash and it appears the following:

    * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[__NSArrayM insertObject:atIndex:]: object cannot be nil'

    Any ideas??? Thanks!!!

  • saimonx
    saimonx over 12 years
    You mean to check if the managedObjectModel is nil? In the -(NSManagedObjectModel *)managedObjectModel; This is already checked. Is in this method where it fails.
  • Rahul Vyas
    Rahul Vyas over 12 years
    No where you are inserting the object in mutable array. The crash is due to attempt to insert a nil object. I think you should use self. managedObjectContext because you are using properties. Otherwise if you pass managedObjectContext to another class you will get a crash.
  • solydest
    solydest almost 12 years
    I don't know about the OP, but this definitely worked for me. Thanks! I've been searching for this answer all day.
  • PKCLsoft
    PKCLsoft about 11 years
    This answer has nothing to do with the actual problem. Virtually all of the other answers are actually on the money. This is not a problem that could be fixed by changing his code. It's an environmental problem caused by Xcode as a result of doing something with the model file.
  • PKCLsoft
    PKCLsoft about 11 years
    Works fine for me too, and for me it was something that happened after renaming the model file.
  • mikecsh
    mikecsh almost 11 years
    You can just do a clean build instead of this. Command-Shift-K to clean, then build and run as usual.
  • JosephH
    JosephH over 10 years
    Unfortunately this answer isn't helpful - the invalid call is happening inside Apple's core data framework; the fix is not to have an invalid coredata model.
  • jamil ahmed
    jamil ahmed almost 10 years
    I had this issue, but was able to fix it's internal reference by selecting an old version of the schema, then re-selecting my newly renamed version. And resetting the simulator.