2012-03-10 47 views
-1

有一些我不明白的核心數據。 我創建了NSManagedDocument,進行了更改並保存了它。 然後我創建了另一個並打開了我保存的文件。 從我的理解NSManagedDocument應該有變化我瘋了,但它沒有。當我打開一個NSManagedDocument(核心數據)文件時,它似乎總是空的

這裏是我寫的代碼:

NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 
url = [url URLByAppendingPathComponent:@"Data Base"]; 
// url is now "<Documents Directory>/Default Photo Database" 
self.dataBase = [[UIManagedDocument alloc] initWithFileURL:url]; 

if (self.dataBase.documentState == UIDocumentStateClosed) { 
    [self.dataBase openWithCompletionHandler:^(BOOL success) { 
    }]; 
} 
Position *pos = [NSEntityDescription insertNewObjectForEntityForName:@"Position" inManagedObjectContext:self.dataBase.managedObjectContext]; 
pos.name = @"positon 1"; 


[self.dataBase saveToURL:self.dataBase.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:^(BOOL success){ 

}]; 

self.dataBase = [[UIManagedDocument alloc] initWithFileURL:url]; 

if (self.dataBase.documentState == UIDocumentStateClosed) { 
    [self.dataBase openWithCompletionHandler:^(BOOL success) { 
    }]; 
} 
pos = [NSEntityDescription insertNewObjectForEntityForName:@"Position" inManagedObjectContext:self.dataBase.managedObjectContext]; 
pos.name = @"position 2"; 

至於我明白,我現在應該已經對實體「位置」 2個對象,但我只有最後一個,這是爲什麼?

我在這裏錯過了什麼?

+0

請發表一些代碼,您創建您的託管對象,以及如何使用NSManagedDocument。如果您能夠獲得調用堆棧或任何其他有關崩潰的有用信息,這也會很好。 – 2012-03-10 13:34:55

回答

0

我不知道爲什麼,但只要我搬到我的代碼它解決了AppDelegate中......

0

我知道這是一個古老的線程,但想我會回答也無妨...... 打開數據庫是一個異步調用。您需要將您將代碼插入到數據庫中的代碼移入完成處理程序的成功塊,否則這將不起作用。你寫它的方式是在數據庫實際打開之前嘗試插入位置。

if (self.dataBase.documentState == UIDocumentStateClosed) { 
    [self.dataBase openWithCompletionHandler:^(BOOL success) { 
     Position *pos = [NSEntityDescription insertNewObjectForEntityForName:@"Position" inManagedObjectContext:self.dataBase.managedObjectContext]; 
     pos.name = @"positon 1"; 
    }]; 
} 
相關問題