将 CoreData 添加到现有 iOS 项目 - 无法获取 NSManagedObjectModel
Posted
技术标签:
【中文标题】将 CoreData 添加到现有 iOS 项目 - 无法获取 NSManagedObjectModel【英文标题】:Adding CoreData to existing iOS project - can't get NSManagedObjectModel 【发布时间】:2011-11-28 11:38:49 【问题描述】:我正在尝试将 CoreData 添加到在 Xcode 4.2 中创建的现有 ios 应用程序中。由于它是基于标签栏的应用程序,我没有在创建时默认包含它的选项。
到目前为止,我已经:
将 CoreData.framework 添加到应用程序(在构建目标中确认) 添加了模型“model.coredatamodeld”(在构建目标中确认,在 iOS 模拟器中运行时确认“mom”文件包含在应用程序目录中) 将应用委托替换为来自启用了 CoreData 的新应用的自动生成版本我最终创建的对象模型返回 nil。如果我查看生成的 URL,它是明智的,它指向我文件系统中的“妈妈”文件夹。该文件夹包含“model.momd”和“VersionInfo.plist”。这两个文件都有合理的内容(前者是一些二进制数据,后者是一些听起来合理的 XML)。
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL: modelURL];
// __managedObjectModel is nil here
如何调试这个?
以下应用委托的来源。
#import "AppDelegate.h"
#import <CoreData/CoreData.h>
@implementation AppDelegate
@synthesize window = _window;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
// Override point for customization after application launch.
id ctx = self.managedObjectContext;
//id model = [self managedObjectModel];
//NSLog(@"%@ %@", ctx, model);
return YES;
- (void)applicationWillTerminate:(UIApplication *)application
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
- (void)saveContext
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
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.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
#pragma mark - Core Data stack
/**
Returns the managed object context for the application.
If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
*/
- (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 from the application's model.
*/
- (NSManagedObjectModel *)managedObjectModel
if (__managedObjectModel != nil)
return __managedObjectModel;
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"model" withExtension:@"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL: modelURL];
NSError *error = nil;
NSData *objectIDData = [NSData dataWithContentsOfURL:modelURL options:NSDataReadingMapped error:&error];
NSLog(@"%@",objectIDData);
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 = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"model.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.
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.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
return __persistentStoreCoordinator;
#pragma mark - Application's Documents directory
/**
Returns the URL to the application's Documents directory.
*/
- (NSURL *)applicationDocumentsDirectory
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
@end
【问题讨论】:
【参考方案1】:我在这方面浪费了足够多的时间,只是简单地创建了一个具有所需“基本功能”(核心数据、故事板、ARC 等)的新项目,然后将我的代码放入其中。并不是真正的最佳解决方案,但只花了大约 10 分钟,更重要的是,它奏效了。
【讨论】:
我遇到了同样的问题,除了它是使用版本化的数据模型。关于配置的一些东西似乎被淹没了。我最终复制了我的模型文件(在我的情况下是原始版本),并将其粘贴到桌面上。然后我删除了我所有的数据模型文件(来自 svn 和文件系统),并将 vanilla 数据模型添加回我的项目。现在一切正常。只有调试受到影响...存档/分发没有任何问题。以上是关于将 CoreData 添加到现有 iOS 项目 - 无法获取 NSManagedObjectModel的主要内容,如果未能解决你的问题,请参考以下文章
使用 Objective-C 将 CoreData 添加到现有项目中
将 Core Data 添加到现有 Xcode 项目时出现未声明的标识符错误
Swift 中适用于 iOS 9 和 iOS 10 的 CoreData 堆栈