保存的Core数据在应用程序关闭80%的时间后不会保留 [英] Saved Core Data does not persist after app closes 80% of the time

查看:88
本文介绍了保存的Core数据在应用程序关闭80%的时间后不会保留的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始处理Core Data,在我的测试中,我发现大约有20%的时间数据被保存到DB。其余时间,它只是暂时保存,而应用程序正在运行。如果我重新启动,我保存的最后一个数据会丢失。

I started dealing with Core Data lately, and in my tests, I've found that about 20% of the time the data actually gets saved to the DB. The rest of the time, it's only saved temporarily, while the app is running. If I restart, the last data I saved gets lost.

有人知道问题是什么?

这里是代码:

//Save data
NSEntityDescription *users = [NSEntityDescription insertNewObjectForEntityForName:@"Users" inManagedObjectContext:document.managedObjectContext];
[users setValue:@"Name Test" forKey:@"name"];
[users setValue:[NSNumber numberWithInt:20] forKey:@"age"];
[users setValue:@"Some Country" forKey:@"location"];


//Debugging
//no error ever shows up
NSError *error;
if(![document.managedObjectContext save:&error]) {
    NSLog(@"Error: %@", error);
}

//this is just to show that the problem may not be with my UIManagedDocument (self.document), since the NSLog never gets called.
if(self.document.documentState != UIDocumentStateNormal) {
    NSLog(@"Document is not opened");
}
//End of debugging


//Fetch all the data from the entity
NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"Users"];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
fetch.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];

NSArray *results = [document.managedObjectContext executeFetchRequest:fetch error:nil];
NSLog(@"Results on the database: %d", [results count]);



我希望这样,在大多数情况下) self.document ;

这里是我的.h和.m的代码:

Here's the code for my .h and .m:

.h:

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

@interface CoreDataViewController : UIViewController

@property (nonatomic, strong) UIManagedDocument *document;

@end

.m: / p>

.m:

#import "CoreDataViewController.h"

@implementation CoreDataViewController
@synthesize document = _document;

- (void)fetchStuff:(UIManagedDocument *)document {

    //Save data
    NSEntityDescription *users = [NSEntityDescription insertNewObjectForEntityForName:@"Users" inManagedObjectContext:document.managedObjectContext];
    [users setValue:@"Name Test" forKey:@"name"];
    [users setValue:[NSNumber numberWithInt:20] forKey:@"age"];
    [users setValue:@"Some Country" forKey:@"location"];


    //Debugging
    //no error ever shows up
    NSError *error;
    if(![document.managedObjectContext save:&error]) {
        NSLog(@"Error: %@", error);
    }

    //this is just to show that the problem may not be with my UIManagedDocument (self.document), since the NSLog never gets called.
    if(document.documentState != UIDocumentStateNormal) {
        NSLog(@"Document is not opened");
    }
    //End of debugging


    //Fetch all the data from the entity
    NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"Users"];
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
    fetch.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];

    NSArray *results = [document.managedObjectContext executeFetchRequest:fetch error:nil];
    NSLog(@"Results on the database: %d", [results count]);
}

- (void)useDocument {
    if(![[NSFileManager defaultManager] fileExistsAtPath:[self.document.fileURL path]]) {
        [self.document saveToURL:self.document.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){
            if(success == YES) NSLog(@"created");
            [self fetchStuff:self.document];
        }];
    } else if(self.document.documentState == UIDocumentStateClosed) {
        [self.document openWithCompletionHandler:^(BOOL success) {
            if(success == YES) NSLog(@"opened");
            [self fetchStuff:self.document];
        }];
    } else if(self.document.documentState == UIDocumentStateNormal) {
        [self fetchStuff:self.document];
    }
}

- (void)setDocument:(UIManagedDocument *)document {
    if(_document != document) {
        _document = document;
        [self useDocument];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if(!self.document) {
        NSURL *url = [[[NSFileManager defaultManager]URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
        url = [url URLByAppendingPathComponent:@"Database"];
        self.document = [[UIManagedDocument alloc]initWithFileURL:url];
    }
}

@end

注:还有我的数据模型,它有一个名为Users的实体,其属性为age,location,name。

Note: There's also my data model, which has an entity called "Users", with the attributes age, location, name.

推荐答案

数据被保存有时是因为自动保存,这发生在每个X(也许10,我需要检查文档)秒。要强制保存,我应该使用这个:

The data was being saved sometimes because of the autosaving, which happens each X (maybe 10, I need to check on documentation) seconds. To force the save, I should've used this:

[documentation saveToURL:documentation.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:^(BOOL success) {
if(success == YES) NSLog(@"Awesome, it's saved!");
}];

虽然它可以很好地添加这个代码到fetchStuff :,最好实现用户退出屏幕,因为它可以通过自动保存自动保存。

Although it works fine adding this code to fetchStuff:, it'd be better to implement this when the user exits the screen, since it could be automatically saved via autosave.

这篇关于保存的Core数据在应用程序关闭80%的时间后不会保留的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆