2012-03-07 29 views
1

我最近開始處理核心數據,在我的測試中,我發現大約20%的時間數據實際保存到數據庫。剩下的時間,它只是暫時保存,而應用程序正在運行。如果我重新啓動,我保存的最後數據會丟失。在應用關閉80%的時間後,保存的核心數據不會持久

有誰知道這個問題可能是什麼?

下面的代碼:

//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]); 

document是同樣的事情(至少我希望如此,在大多數情況下)爲self.document;這只是該代碼所在方法的一個參數。

下面是我的.h和.M代碼:

.H:

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

@interface CoreDataViewController : UIViewController 

@property (nonatomic, strong) UIManagedDocument *document; 

@end 

.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 

注:還有我的數據模型,它有一個名爲「用戶」的實體,具有屬性年齡,位置,名稱。

+0

嗯,間歇性的錯誤很難找到,儘量儘量張貼代碼。在另一個說明中,看看MagicalRecord(https://github.com/magicalpanda/MagicalRecord),我最近一直在使用它,這讓我的許多常見核心數據任務變得更輕鬆。 – allaire 2012-03-07 21:39:06

+1

如果您的應用程序未運行,您將如何保存? – Mundi 2012-03-07 21:43:27

+0

allaire,我剛剛發佈了我的頭文件和實現文件的代碼。我會看看MagicalRecord,謝謝! – 2012-03-07 22:14:46

回答

6

數據被保存有時是因爲autosaving,這發生在每個X(可能是10,我需要檢查文檔)秒。要強制保存,我應該用這樣的:

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

雖然它工作正常,將此代碼添加到fetchStuff :,它會是更好地實現這個當用戶退出屏幕,因爲它可以自動通過自動保存保存。

+1

謝謝你,這是我能找到的唯一解決方案!一直試圖對它進行排序!沒有人建議已經工作! – simonthumper 2013-05-04 13:43:33

2

您不應該在UIManagedDocument MOC上調用保存。這裏是你的代碼的編輯版本。請嘗試。

//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"]; 

// Removed save on UIMDMOC - We let auto-save do the work 
// However, we have to tell the document that it needs to 
// be saved. Now, the changes in the "main" MOC will get pushed 
// to the "parent" MOC, and when appropriate, will get save to disk. 
[document updateChangeCount:UIDocumentChangeDone]; 

if(self.document.documentState != UIDocumentStateNormal) { 
    NSLog(@"Document is not opened"); 
}  

//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]); 

OK ......這是不是太痛苦了......只是刪除了通話保存,並用電話,告訴UIManagedDocument,有些已經作了修改,並需要保存取而代之。

+0

但是,這會立即保存文檔還是等待10秒? – 2017-02-02 22:00:21

0
Record *newentry = [NSEntityDescription insertNewObjectForEntityForName:@"Record" inManagedObjectContext:self.mManagedObjectContext]; 
    newentry.code = entryStr; 
    NSError *error; 
    if ([self.mManagedObjectContext save:&error]) 
    { 
     NSLog(@"save successfully"); 
    } 
    else 
    { 
     NSLog(@"fail to save"); 
    } 
相關問題