2010-06-12 28 views
1

我有一個關於使用KVO兼容方法從數組插入/刪除對象的問題。我工作過艾倫·希爾加斯可可規劃爲Mac OS X和我看到下面的代碼行(在insertObject:inEmployeesAtIndex:方法:mutableArrayValueForKey和調用insertObject之間的區別:inEmployeesAtIndex:直接

[[undoManager prepareWithInvocationTarget:self] removeObjectFromEmployeesAtIndex:index]; 

糾正我,如果我錯了,但我一直認爲這是更好調用mutableArrayValueForKey:然後removeObjectAtIndex: ...所以我試圖改變上述行來此:

[[undoManager prepareWithInvocationTarget:[self mutableArrayValueForKey:@"employees"]] removeObjectAtIndex:index]; 

而且它沒有工作一個人能解釋的區別,爲什麼第一線工作,但第二行沒有按」 t?

UP DATE:我的removeObjectFromEmployeesAtIndex:index方法被實現來使我的集合類(一個NSMutableArray的實例)符合KVC。所以最終,呼叫[[self mutableArrayValueForKey:@"employees"] removeObjectAtIndex:index];應該最終打電話[self removeObjectFromEmployeesAtIndex:index];

回答

1

在你更新你說:

調用[自我mutableArrayValueForKey:@ 「僱員」] removeObjectAtIndex:指數]應該最終調用[self removeObjectFromEmployeesAtIndex:index];

不幸的是,這是不正確的,無論你的removeObjectFromEmployeesAtIndex:方法是什麼,因爲NSMutableArray永遠不會調用你的類中的任何方法。既然你似乎試圖獲得撤銷/重做功能,你必須使用像removeObjectFromEmployeesAtIndex:這樣的方法。否則,當您添加員工時,您將無法「重做」添加該員工。您也可能在撤銷/重做時遇到個別員工編輯方面的問題。如果你想要你可以改變removeObjectFromEmployeesAtIndex:方法中的一行[employees removeObjectAtIndex:index];[[self valueForKey:@"employees"] removeObjectAtIndex:index];[self.employees removeObjectAtIndex:index];,但是沒有理由走這條路線。

0

是的。第一行(從書)基本上是相同的:

id tmp = [undoManager prepareWithInvocationTarget:self]; 
[tmp removeObejctFromEmployeesAtIndex:index]; 

您的代碼,但是,基本上是相同的:

id tmp1 = [self mutableArrayValueForKey:@"employees"]; 
id tmp2 = [undoManager prepareWithInvocationTarget:tmp1]; 
[tmp2 removeObjectAtIndex:index]; 

換句話說,目標是你準備您的代碼中的調用與您的代碼中的不同(除非self恰好與[self mutableArrayValueForKey:@"employees"]相同,這是值得懷疑的)。

+0

哦,對不起,我感到困惑。我更新了一些更詳細的信息。但實際上,我確實想調用-removeObjecAtIndex:on [self mutableArrayValueForKey:@employees「] – jasonbogd 2010-06-30 02:35:12