2011-08-14 60 views
0

我在Lion中使用了一項新功能,子託管對象上下文用於:「管理可放棄的編輯,例如在檢查器窗口或視圖中。臨時託管對象ID和子託管對象上下文

當我從父MOC傳遞一個託管對象ID到子MOC時,如果父MOC從未保存過,我會得到一個錯誤:「嘗試訪問未在存儲中找到的對象。

NSManagedObjectContext *parentContext = [(NSPersistentDocument *)[[[self window] windowController] document] managedObjectContext]; 

self.subMOC = [[[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType] autorelease]; 

[subMOC setParentContext:parentContext]; 

NSManagedObjectID *objectValueID = [[[self superview] valueForKey:@"objectValue"] objectID]; 

self.subObjectValue = [subMOC existingObjectWithID:objectValueID error:&err]; 

上面的工作很好,如果文檔已被保存。如果沒有保存,我有什麼選擇?

回答

2

在MOC保存之前,任何對象ID都是臨時的,您必須保存上下文以獲取「真實」對象ID。我不知道任何解決方法。

編輯:

我的意思是,很明顯,你可以做

if (parentContext.hasChanges) { 
     [panrentContext save:nil]; 
} 
0

答案,而不需要保存,是使用提取請求。此代碼,這是非常接近的是在文檔中,工作對我來說:

NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:subMOC]; 
[request setEntity:entity]; 

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self == %@", [[self superview] valueForKey:@"objectValue"]]; 
[request setPredicate:predicate]; 

err = nil; 
NSArray *array = [subMOC executeFetchRequest:request error:&err]; 
if (array != nil) 
{ 
    self.subObjectValue = [array objectAtIndex:0]; 
} 

在項目中,我仍然使用的代碼從上面的問題,並僅當沒有使用fetch請求。

+0

這不是一個線程安全的方法,如果它擔心你。你在這裏傳遞對象。使用託管對象ID是安全的。但是,我堅持你是一樣的情況:) –

相關問題