1
votes

I'm entirly new to creating iOS apps. I have to quickly create a form-application where I can store information from people willing to fill it in. Basicly just a bunch of text-fields for stuff like name, mail etc.

Once the form is filled, I'm storing their data with this bit of code:

//Save action
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Person" inManagedObjectContext: context];
NSManagedObject *newPerson = [[NSManagedObject alloc]initWithEntity:entityDesc insertIntoManagedObjectContext:context];

//Fill in values
[newPerson setValue:self.btnPrefix.titleLabel.text forKey: @"prefix"];
[newPerson setValue:self.txtFirstName.text forKey: @"firstname"];
[newPerson setValue:self.txtLastName.text forKey: @"lastname"];
[newPerson setValue:self.txtLive.text forKey: @"country"];
[newPerson setValue:self.txtMail.text forKey: @"email"];
[newPerson setValue:self.txtPhone.text forKey: @"phonenumber"];
[newPerson setValue:self.txtLinked.text forKey: @"linkedIn"];
[newPerson setValue:self.txtAbout.text forKey: @"about"];

NSError *error;
[context save:&error];

When executed on the simulator no problem at all. But once ran on the iPad I get this error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Person''

After debugging it gets triggerd on the first line:

NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Person" inManagedObjectContext: context];

After a bit more research, my Appdelegate contains a nil persistentContainer when ran on device, but it's filled when ran on virtual device. So I guess the problem is there, but I can't find a way to solve it.

- (void)viewDidLoad {
    [super viewDidLoad];
    AppDelegate *appdelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
    context = appdelegate.persistentContainer.viewContext;
}

Can anyone help me out?

2
The error tells you that your context parameter is nil, which must not be the case. How do you get the managed object context object you're passing in there? And I assume you have ensured that your model does contain an Entity with the name "Person", right?Gero
under viewDidLoad AppDelegate *appdelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate]; context = appdelegate.persistentContainer.viewContext;. And yes I have a model that contains the entity Person. As I said it works on the simulator so I imagine there's just a thing missing to make it work on a physical device?Akorna
After a bit more research, my Appdelegate contains a nil persistentContainer when ran on device, but it's filled when ran on virtual device. So I guess the problem is there, but I can't find a way to solve it.Akorna
I assume you're just using a standard template for core data. So why not look into the persistentContainer method your app delegate has by default? It sounds like you're either trying to initiate a container in a location you don't have write access to on the device (the simulator usually has more write permissions in various places) or you're facing a racing condition on device (your view controller tries to access the container and context before the loadPersistentStoresWithCompletionHandler: method is done).Gero
No problem, it just seemed to me it was a bit "early" to ask, but I realize what is "too early" and what not depends on the individual and you did say you were new. I am glad you found the root of this, I guess now you can see this would have been hard to figure out for anybody who hasn't your project right in front of them AND has had a similar experience. I wanted to prevent that you might come to the conclusion people on SO are "above" helping a new coder. :) Again, I am glad you figured it out on your own.Gero

2 Answers

2
votes

For those encountering this error. Most probably if it works on the virtual device but not on the physical device it's due to the differences for accessing core data between iOS 9 and 10.

In Xcode 8 the AppDelegate automaticly generates data for iOS 10 but if you're stuck on iOS 9 you'll need to add the following code in your delegate file:

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *) applicationDocumentsDirectory{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    if(_managedObjectModel != nil){
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"StylelabsForms" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *) persistentStoreCoordinator{
    if(_persistentStoreCoordinator != nil){
        return _persistentStoreCoordinator;
    }

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"StylelabsForms.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"Error loading saved data";
    if(![_persistentStoreCoordinator addPersistentStoreWithType: NSSQLiteStoreType configuration:nil URL: storeURL options:nil error:&error]){
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed init application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}

- (NSManagedObjectContext *) managedObjectContext {
    if (_managedObjectContext != nil){
        return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if(!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];

    return _managedObjectContext;
}

Also adapt the save as followed:

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if(managedObjectContext != nil){
        NSError *error = nil;
        if([managedObjectContext hasChanges] && ![managedObjectContext save:&error]){
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }

    //For iOS 10 and above
    /*
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context 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.
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    } */
}
0
votes

private lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }()

private lazy var managedObjectModel: NSManagedObjectModel = {
    // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
    let modelURL = Bundle.main.url(forResource: "CoreData", withExtension: "momd")!
    return NSManagedObjectModel(contentsOf: modelURL)!
}()

private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
    // Create the coordinator and store
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.appendingPathComponent("CoreData.sqlite")
    var failureReason = "There was an error creating or loading the application's saved data."
    do {
        // Configure automatic migration.
        let options = [ NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true ]
        try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)
    } catch {
        // Report any error we got.
        var dict = [String: AnyObject]()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
        dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?

        dict[NSUnderlyingErrorKey] = error as NSError
        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
        // Replace this 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.
        NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
        abort()
    }

    return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext = {

    var managedObjectContext: NSManagedObjectContext?
    if #available(iOS 10.0, *){

        managedObjectContext = self.persistentContainer.viewContext
    }
    else{
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
    let coordinator = self.persistentStoreCoordinator
    managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext?.persistentStoreCoordinator = coordinator

    }
    return managedObjectContext!
}()
// iOS-10
@available(iOS 10.0, *)
lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
     */
    let container = NSPersistentContainer(name: "CoreData")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() 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.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error)")
        }
    })
    print("\(self.applicationDocumentsDirectory)")
    return container
}()