【问题标题】:Difference between mutableArrayValueForKey and calling insertObject:inEmployeesAtIndex: directlymutableArrayValueForKey 和直接调用 insertObject:inEmployeesAtIndex: 的区别
【发布时间】:2010-06-12 05:32:30
【问题描述】:

我有一个关于使用符合 KVO 的方法从数组中插入/删除对象的问题。我正在研究 Aaron Hillegass 的 Cocoa Programming for Mac OS X,我看到了以下代码行(在 insertObject:inEmployeesAtIndex: 方法中:

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

如果我错了,请纠正我,但我一直认为最好先拨打mutableArrayValueForKey:,然后拨打removeObjectAtIndex:...所以我尝试将上面的行改为:

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

但它没有用。有人可以解释其中的区别以及为什么第一行有效而第二行无效吗?

更新:我的 removeObjectFromEmployeesAtIndex:index 方法被实现以使我的集合类(NSMutableArray 的一个实例)符合 KVC。所以最终,调用[[self mutableArrayValueForKey:@"employees"] removeObjectAtIndex:index]; 应该最终调用[self removeObjectFromEmployeesAtIndex:index];

【问题讨论】:

    标签: cocoa cocoa-bindings key-value-observing


    【解决方案1】:

    在你的更新中你说:

    调用 [[self mutableArrayValueForKey:@"employees"] removeObjectAtIndex:index];应该最终调用 [self removeObjectFromEmployeesAtIndex:index];

    不幸的是,无论您的 removeObjectFromEmployeesAtIndex: 方法中有什么,这都不正确,因为 NSMutableArray 永远不会调用您类中的任何方法。由于您似乎试图获得撤消/重做功能,因此您必须使用removeObjectFromEmployeesAtIndex: 之类的方法。否则,当您点击撤消添加员工时,您将无法“重做”添加该员工。对于个别员工的编辑,您还可能遇到撤消/重做的问题。如果您愿意,可以将 removeObjectFromEmployeesAtIndex: 方法中的行更改为 [employees removeObjectAtIndex:index];[[self valueForKey:@"employees"] removeObjectAtIndex:index];[self.employees removeObjectAtIndex:index];,但实际上没有理由走这条路。

    【讨论】:

      【解决方案2】:

      是的。第一行(来自书中)基本上相当于这样:

      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"] 相同的对象,这是值得怀疑的)。

      【讨论】:

      • 哦,很抱歉造成混乱。我用更多细节更新了帖子。但实际上,我确实想调用 -removeObjecAtIndex: on [self mutableArrayValueForKey:@employees"]
      猜你喜欢
      • 2014-03-05
      • 2013-07-17
      • 2012-06-02
      • 1970-01-01
      • 2015-11-03
      • 1970-01-01
      • 2020-04-20
      • 2018-05-26
      相关资源
      最近更新 更多