[英]Core Data is not persisting data between app launches
我有一個使用核心數據的應用程序。 正在創建核心數據堆棧(上下文,對象圖,持久性存儲協調器和持久性存儲),並且我可以毫無問題地使用它。 問題是保存的數據無法持久保存,有人可以幫我解決我做錯的事情嗎? 這是我創建核心數據堆棧的地方。
- (void)initializeCoreDataStack
{
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Favorites"
withExtension:@"momd"];
if (!modelURL)
NSLog(@"MODEL URL NOT INITIALIZED");
NSManagedObjectModel *mom = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
if (!mom)
NSLog(@"OBJECT MODEL NOT CREATED");
NSPersistentStoreCoordinator * psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
if (!psc)
NSLog(@"PERSISTENT STORE COORDINATOR NOT CREATED");
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[moc setPersistentStoreCoordinator:psc];
self.managedObjectContext = moc;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSArray *directory = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask];
NSURL *storeUrl = [directory lastObject];
storeUrl = [storeUrl URLByAppendingPathComponent:@"Favorites.sqlite"];
NSError *error = nil;
NSPersistentStore *store = [psc addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeUrl
options:nil
error:&error];
if (!store)
{
NSLog(@"ERROR CREATING STORE: %@ %@", error.localizedDescription, error.domain);
// present error to user
}
else
{
dispatch_sync(dispatch_get_main_queue(), ^{
// do something once the stack is finished being created
NSLog(@"persistent store created");
});
}
});
}
您必須明確保存核心數據,否則它將不會持久保存。 不過,這並不難解決。
在控制器實現文件(例如coreDataViewController.m)中,要保存對核心數據的更改時調用此函數
// add this call, whenever you want to save data
// e.g. responding to a UIButton event
[self saveCoreDataContext];
- (void)saveCoreDataContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
我的個人經驗是,即使您調用了[moc save:error],在從Xcode->構建並在設備上運行應用程序時,也可能找不到保存的內容。 但是,如果停止Xcode運行該應用程序,然后通過單擊“應用程序圖標”從設備啟動該應用程序,則該內容實際上將保留下來。
只是我通過反復試驗發現的個人經驗,希望您能看到同樣的事情。
您必須保存MOC。
[mom save:nil];
這里有些事情對我來說很奇怪。 首先,為什么要穿線創建NSPersistentStore
? 通常,我創建NSPersistentStoreCoordinator
,添加NSPersistentStore
,然后創建上下文。 除非您有充分的理由,否則我建議您以該順序進行。 盡管沒有特別禁止,但是在創建NSManagedObjectContext
之后,添加NSPersistentStore
可能會遇到問題。
我不確定是否需要它,但是我一直明確地強烈引用NSPersistentStoreCoordinator
。 同樣,創建多個上下文也很有用。 我建議在您的代碼中這樣做。
正如其他所有人所說,您還需要顯式保存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.