xcode 核心数据应用程序在 iphone 设备中崩溃

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6706505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 21:29:23  来源:igfitidea点击:

core data application is Crashing in iphone device

iphonexcodecore-data

提问by iProgrammer

Hello I am testing my core data application in device, but it is crashing in iphone and working fine in simulator.Here is my code..

您好,我正在设备中测试我的核心数据应用程序,但它在 iphone 中崩溃并在模拟器中正常工作。这是我的代码..

- (NSManagedObjectContext *)managedObjectContext {

    if (managedObjectContext != nil) {
        return managedObjectContext;

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



- (NSManagedObjectModel *)managedObjectModel {

    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"TouristGuide" withExtension:@"momd"];
    managedObjectModel= [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];    
    NSLog(@"%@", modelURL);
    return managedObjectModel;
}


- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {


    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }

    NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"TouristGuide.sqlite"];


    NSFileManager *fileManager = [NSFileManager defaultManager];
    // If the expected store doesn't exist, copy the default store.
    if (![fileManager fileExistsAtPath:storePath]) {
        NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"TouristGuide" ofType:@"sqlite"];
        if (defaultStorePath) {
            [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
        }
    }

    NSURL *storeUrl = [NSURL fileURLWithPath:storePath];


    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];    
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];


    NSError *error;
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
        // Update to handle the error appropriately.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        exit(-1);  // Fail
    }    


    return persistentStoreCoordinator;
}

device log is showing exception in line:

设备日志显示异常:

persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];

The exceptions are cannot create nspersistancecordinator with a nil modeland second is cannot find Entity 'City'.

例外是cannot create nspersistancecordinator with a nil model,第二个是cannot find Entity 'City'

How can I solve this problem?

我怎么解决这个问题?

Crash log

崩溃日志

0x352d1de0 -[NSPersistentStoreCoordinator initWithManagedObjectModel:] + 252 10  TouristGuide                   
0x0000358e -[TouristGuideAppDelegate persistentStoreCoordinator] (TouristGuideAppDelegate.m:176) 11  TouristGuide                  
0x0000310e -[TouristGuideAppDelegate managedObjectContext] (TouristGuideAppDelegate.m:124) 12  TouristGuide     
0x000041f6 -[CityViewController viewDidLoad] (CityViewController.m:43)

回答by CommaToast

Hold down the option key, go to Productmenu (Xcode 4) and do "Clean Build Folder"... then let off the option key, and do "Clean"...

按住选项键,转到产品菜单(Xcode 4)并执行“清理构建文件夹”...然后松开选项键,然后执行“清理”...

Now do Productmenu > Analyze and make sure all is kosher.

现在做产品菜单>分析并确保一切都是犹太洁食。

Lastly go to the left hand panel of the project viewer, and click on the icon that represents your entire project. In the window that comes up in the main panel, under "Targets," click on your app. Now click "Build Phases" and expand "Copy Bundle Resources." Make sure that your TouristGuide.xcdatamodeld file is there. Next, expand "Link Binary with Libraries" and make sure that "CoreData.framework" is in there (if you added Core Data to an existing project that didn't start out as a Core Data project, then chances are, it's not in there). Next, expand "Compile Sources" and, of course, double-check that all your model classes are in there (y'know, the NSManagedObject custom sub-classes).

最后转到项目查看器的左侧面板,然后单击代表整个项目的图标。在主面板中出现的窗口中,在“目标”下,单击您的应用程序。现在单击“构建阶段”并展开“复制捆绑资源”。确保您的 TouristGuide.xcdatamodeld 文件在那里。接下来,展开“Link Binary with Libraries”并确保“CoreData.framework”在其中(如果您将 Core Data 添加到一个不是作为 Core Data 项目开始的现有项目,那么很可能它不在那里)。接下来,展开“编译源”,当然,仔细检查所有模型类是否都在其中(您知道,NSManagedObject 自定义子类)。

Speaking of those model classes... now click on your TouristGuide.xcdatamodeld and click on the "Default" configuration. Make sure any classes that say "NSManagedObject" in the "Class" column do NOT have custom classes, and if they do list a custom class, make sure you have the equivalently-named .h and .m files corresponding to those.

说到那些模型类……现在单击您的 TouristGuide.xcdatamodeld 并单击“默认”配置。确保在“类”列中显示“NSManagedObject”的任何类都没有自定义类,如果它们确实列出了自定义类,请确保您具有与它们对应的等效命名的 .h 和 .m 文件。

10-to-1 it's something to do with your model file itself. Onetime I changed my model file's full path (it should be /Users/You/Documents/Developer/MyApp/MyModel.xcdatamodeld/MyModel.xcdatamodel). Once I had changed it, I couldn't figure out how to change it back, because MyModel.xcdatamodeld is a "package" file, not a folder. Sure, in the finder, you can do "Show Package Contents...", but XCode's dialog box for picking the file's location refused to navigate intothe package contents! SO I was unable to ever re-select the .xcdatamodel file that resides within the .xcdatamodeld file! I had to totally recreate my entire model file from scratch, it was a huge pain. Maybe there's a way to do it but I couldn't figure it out.

10 比 1 这与您的模型文件本身有关。有一次我更改了模型文件的完整路径(它应该是 /Users/You/Documents/Developer/MyApp/MyModel.xcdatamodeld/MyModel.xcdatamodel)。一旦我改变了它,我就想不出如何把它改回来,因为 MyModel.xcdatamodeld 是一个“包”文件,而不是一个文件夹。当然,在查找器中,您可以执行“显示包内容...”,但是 XCode 用于选择文件位置的对话框拒绝导航包内容!所以我无法重新选择位于 .xcdatamodeld 文件中的 .xcdatamodel 文件!我不得不从头开始完全重新创建我的整个模型文件,这是一个巨大的痛苦。也许有办法做到这一点,但我无法弄清楚。

Also, two last tricks.

另外,最后两个技巧。

First last trick, try this on a backup of your project just in case, but it worked for me when I got stuck: change your code from this:

最后一个技巧,为了以防万一,在你的项目的备份上试试这个,但是当我卡住时它对我有用:从这个改变你的代码:

NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"TouristGuide" withExtension:@"momd"];

to this:

对此:

NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"TouristGuide" withExtension:@"mom"];

...change "momd" to "mom".

...将“妈妈”更改为“妈妈”。

Then delete the app from device or simulator, "Clean build folder," "clean," and rebuild and re-run the project. It might give you errors, it might not. After that, then change it back to "momd" and redo all those steps. Changing this will might make XCode delete more stuff than it otherwise would when you do "Clean Build Folder" and reinstall the app. That way it's making a fresh "momd" file when you switch back.

然后从设备或模拟器中删除应用程序,“清理构建文件夹”,“清理”,然后重建并重新运行项目。它可能会给你错误,也可能不会。之后,将其改回“momd”并重做所有这些步骤。更改此设置可能会使 XCode 删除的内容比执行“清理构建文件夹”并重新安装应用程序时要删除的内容多。这样,当您切换回来时,它会创建一个新的“momd”文件。

Second last trick:

倒数第二招:

It also never hurts to #import in your headers, just for good luck. :D

在您的标题中 #import 也永远不会受到伤害,只是为了祝您好运。:D

Hope this helps. If someone would have told me this stuff at the beginning it would have saved me a lot of time.

希望这可以帮助。如果有人在一开始就告诉我这些东西,那会为我节省很多时间。

回答by TechZen

The error is actually caused by the self.managedObjectModelproperty having a nil value. Look at the method where the managedObjectModel is loaded. That is the source of your problem.

该错误实际上是由self.managedObjectModel具有 nil 值的属性引起的。查看加载managedObjectModel 的方法。这就是你问题的根源。

Sometimes, Xcode does not remove previous versions of files from development builds on either the simulator or device. The solution is to manually delete the entire app of device and have Xcode rebuild it from scratch.

有时,Xcode 不会从模拟器或设备上的开发版本中删除以前版本的文件。解决方案是手动删除设备的整个应用程序,并让 Xcode 从头开始​​重建它。