2009-10-03 19 views
4

在Core Data項目中,我的界面(表格)上有兩個按鈕,一個用於編輯關於某人的數據並將其保存到數據庫中,另一個用於讓您直觀地瀏覽數據而不實際保存它的數據庫。 如何「分離」核心數據對象,以便它不會將數據寫入數據庫?我試圖編寫一個模仿NSManagedObject類的新NSObject類,然後將數據移入NSObject類,但它仍然會更改數據庫!如何從Core Data中分離管理對象?

//button for editing and saving 
PersonObj *person = (PersonObj *)[fetchedResultsController objectAtIndexPath:indexPath]; 
PersonEditViewController *editViewController = [[PersonEditViewController alloc] initWithStyle:UITableViewStyleGrouped]; 
// puts the managed object into the new view controller 
editViewController.person = person; 
[self.viewController pushViewController:editViewController animated:animated]; 
[editViewController release]; 

//button for editing and NOT saving 
PersonObj *person = (PersonObj *)[fetchedResultsController objectAtIndexPath:indexPath]; 
PersonFiddlingViewController *fiddling = [[PersonFiddlingViewController alloc] initWithStyle:UITableViewStyleGrouped]; 
// move db data into non-db class??? not working 
fiddling.eyeColor = person.eyeColor; 
fiddling.name = person.name; 
[self.viewController pushViewController:fiddling animated:animated]; 
[fiddling release]; 

回答

0

我只使用核心數據好幾天,現在(只是轉換了一個項目,用它來存儲用戶數據),但你的描述就沒有意義了。除非您在某處使用NSManagedObjectContext:save:來提交更改,否則後備存儲(db)如何保存更改?你可以在你調用該方法的地方發佈你的代碼嗎?也許你錯誤地從一些其他的背景(也許viewDidLoad:什麼的)。

2

我不認爲你明白CD的工作原理。您不能從CoreData分離對象,CD是對象的後備存儲。

我也非常確定您看到的問題與上面包含的代碼無關,因爲即使在第一種情況下,代碼中也沒有任何內容會將更改提交到持久存儲。如果缺少對NSManagedObjectContext:save:的調用,對象圖的所有更改都將是暫時的。

換句話說,爲了做你想做的事(調整東西而不保存它),只需在調整對象後在上下文中調用​​即可。如果您需要保存其他的變化,你可以明確地回滾調整之前保存,或者你可以與他們擺弄之前包裹在自己的範圍內微調的對象:

NSManagedObjectContext *tweakingContext = [[NSManagedObjectContext alloc] init]; 
tweakingContext.persistentStoreCoordinator = person.managedObjectContext.persistentStoreCoordinator; 
PersonObj *tweakablePerson = [tweakingContext objectWithID:person.managedObjectID]; 

//Do your stuff 

[tweakingContext release]; 

上面的代碼會給你新的對象(tweakablePerson)從與人相同的數據中出錯,但在獨立的上下文中,您永遠不會保存。如果你確實想保存它,你可以,但是你將不得不處理其他問題(如果發生其他保存,可能會節省衝突)。

同樣,雖然這回答了您所問的問題,但我認爲它不會解決您的問題,因爲問題幾乎肯定不在提取或對象創建代碼中(您顯示),而是在保存代碼你還沒有列出。

相關問題