Objective c 在Swift中观察多个关系的关键值

Objective c 在Swift中观察多个关系的关键值,objective-c,cocoa,swift,key-value-observing,key-value-coding,Objective C,Cocoa,Swift,Key Value Observing,Key Value Coding,当您想要通知Objective-C中的NSMutableArray的更改时,苹果的文档鼓励您实现可选的可变访问器: 强烈建议您实现这些可变访问器,而不是依赖直接返回可变集[sic]的访问器。在对关系中的数据进行更改时,可变访问器的效率要高得多 至少,为了使设置正常工作,您需要以下内容。(这是非常直截了当的,因为Xcode的代码完成工具会猜测您在做什么,并向您提供签名。) 您说您尝试了使用NSMutableArray,但没有尝试使用var children:[AnyObject]。也许您应该尝试使

当您想要通知Objective-C中的
NSMutableArray
的更改时,苹果的文档鼓励您实现可选的可变访问器:

强烈建议您实现这些可变访问器,而不是依赖直接返回可变集[sic]的访问器。在对关系中的数据进行更改时,可变访问器的效率要高得多

至少,为了使设置正常工作,您需要以下内容。(这是非常直截了当的,因为Xcode的代码完成工具会猜测您在做什么,并向您提供签名。)


您说您尝试了使用
NSMutableArray
,但没有尝试使用
var children:[AnyObject]
。也许您应该尝试使用后者?编辑Swift数组实际上会创建一个新的数组,因此当KVO通知通过
类发出时
仅为
。设置
。我想要更详细一点的东西(比如操作是
.insert
还是
.remove
)。此外,有时可变Swift数组不能直接替代
NSMutableArray
,因此在本例中我想继续使用
NSMutableArray
。谢谢你的建议。
// Assumes the class to which these methods belong has an NSMutableArray
// property called <children>.

-(void)insertObject:(NSNumber *)object inChildrenAtIndex:(NSUInteger)index {
    [self.children insertObject:object atIndex:index];
}

-(void)removeObjectFromChildrenAtIndex:(NSUInteger)index {
    [self.children removeObjectAtIndex:index];
}
// These accessors don't trigger KVO notifications.

func insertObject(object: AnyObject!, inChildrenAtIndex index: Int) {
    children.insertObject(object, atIndex: index)
}

func removeObjectFromChildrenAtIndex(index: Int) {
    children.removeObjectAtIndex(index)
}

func replaceObjectInChildrenAtIndex(index: Int, withObject object: AnyObject!) {
    children.replaceObjectAtIndex(index, withObject: object)
}