2013-10-25 47 views
0

我有一個NSManagedObject斯科特從NSManagedObjectContext context1中獲取。我也有從NSManagedObjectContext context2獲取的同一個Scott。在另一個上下文中更新核心數據實體

我知道如果我從相同的上下文中獲取它們,如果一個更新了,另一個也會更新,但是我目前的結構不會輕易讓我傳遞相同的上下文。我想知道是否有另一種方式,與KVO有關。

當我在context1中對人Scott進行更改時,能否更新context2中的Person Scott?

編輯:

嘗試測試:

NSError *error = nil; 

NSManagedObjectContext *context = [NSManagedObjectContext MR_context]; 
NSManagedObjectContext *context2 = [NSManagedObjectContext MR_context]; 

Boundary *boundary1 = [Boundary MR_findFirstInContext:context]; 
DLog(@"boundary1.name: %@", boundary1.name); 
DLog(@"boundary1.managedObjectContext: %@", boundary1.managedObjectContext); 

Boundary *boundary2 = (Boundary *)[context2 existingObjectWithID:boundary1.objectID error:&error]; 
DLog(@"boundary2.name: %@", boundary2.name); 
DLog(@"boundary2.managedObjectContext: %@", boundary2.managedObjectContext); 

boundary1.name = @"new name"; 

// Added this, does not change results 
[context2 MR_observeContext:context]; 

DLog(@"boundary1.name: %@", boundary1.name); 
DLog(@"boundary1.managedObjectContext: %@", boundary1.managedObjectContext); 

DLog(@"boundary2.name: %@", boundary2.name); 
DLog(@"boundary2.managedObjectContext: %@", boundary2.managedObjectContext); 

結果:

DEBUG | -[LoginViewController viewDidLoad] | boundary1.name: 997677 
DEBUG | -[LoginViewController viewDidLoad] | boundary1.managedObjectContext: <NSManagedObjectContext: 0x1cdc6b20> 
DEBUG | -[LoginViewController viewDidLoad] | boundary2.name: 997677 
DEBUG | -[LoginViewController viewDidLoad] | boundary2.managedObjectContext: <NSManagedObjectContext: 0x1cdd7930> 
DEBUG | -[LoginViewController viewDidLoad] | boundary1.name: new name 
DEBUG | -[LoginViewController viewDidLoad] | boundary1.managedObjectContext: <NSManagedObjectContext: 0x1cdc6b20> 
DEBUG | -[LoginViewController viewDidLoad] | boundary2.name: 997677 
DEBUG | -[LoginViewController viewDidLoad] | boundary2.managedObjectContext: <NSManagedObjectContext: 0x1cdd7930> 

boundary1變化的名稱不持續到boundary2的名字。

回答

3

您可以通過NSManagedObjectID將對象從上下文傳遞給另一個對象。作爲醫生說

管理對象ID唯一地識別相同的管理對象都 管理對象上下文之間在單個應用中,和在 多個應用程序(如在分佈系統)。標識符包含 所需的信息以準確描述持久存儲中的對象(如數據庫中的主鍵)中的對象,儘管詳細的 信息未公開。

基於此,如果您通過id從上下文中傳遞對象,那麼在另一箇中您可以檢索,修改並保存它。前一種情況會看到這些變化。

在上下文中,您可以使用例如existingObjectWithID:error:返回具有指定標識的對象。請參閱What's the difference between -existingObjectWithID:error: and –objectWithID:?和Apple文檔。

讓我知道你是否需要別的東西。

+0

我試過測試解決方案,第一個對象的更改沒有更新其他上下文中的對象。我更新了我的問題。 – Padin215

1

您需要將更改從一個上下文合併到另一個上下文。 因爲它看起來像你使用MagicalRecord你可以做壽輕鬆地:

[context2 MR_observeContext:context1]

+0

我試過這個,不能得到它的工作。我添加到我的編輯。 – Padin215

0

您需要保存,以便其他環境的變化對通過改變所通知

[context MR_saveToPersistentStoreAndWait];

當您保存上下文

[boundary1.managedObjectContext MR_saveToPersistentStoreAndWait];

CoreData實體更新通知將只公佈。您可以將上下文視爲臨時書籍。如果您從context1對實體進行任何更改並且不希望這些更改持久存在,則可以簡單地放棄該上下文(將上下文設置爲nil)並且不會保留任何內容。