我试图观察在ObjectiveC中编写的对象中的NSMutableArray
的值更改。然而观察者是用Swift编写的UIViewController
。 我无法获得KVO通知。这些是我的更改:可以在Swift中编写的UIViewController作为ObjC中写入的对象的观察者
@interface Record : BaseObject
@property (nonatomic) NSMutableArray *commentsArray;
-(NSUInteger) countOfCommentsArray {
return _commentsArray.count;
}
-(id) objectInCommentsArrayAtIndex:(NSUInteger)index {
return [_commentsArray objectAtIndex:index];
}
-(void) insertObject:(Comment *)comment inCommentsAtIndex:(NSUInteger)index {
[_commentsArray insertObject:comment atIndex:index];
}
-(void) insertComments:(NSArray *)array atIndexes:(NSIndexSet*)indexes {
[_commentsArray insertObjects:array atIndexes:indexes];
}
-(void) removeCommentsAtIndexes:(NSIndexSet *)indexes {
[_commentsArray removeObjectsAtIndexes:indexes];
}
-(void) removeObjectFromCommentsAtIndex:(NSUInteger)index {
[_commentsArray removeObjectAtIndex:index];
}
-(void) replaceObjectInCommentsAtIndex:(NSUInteger)index withObject:(id)object {
[_commentsArray replaceObjectAtIndex:index withObject:object];
}
BaseObject派生自NSObject
。
在我的Observer类是一个Viewcontroller,并写在Swift中我有以下。
在设置方法之一。
myInspectionRecord?.addObserver(self, forKeyPath: "commentsArray", options: NSKeyValueObservingOptions.New, context: nil);
而且我有方法overrriden。
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
print("Value Changed");
}
但不知何故,当我使用API本身添加一个新的对象数组,被触发的observeValue
方法似乎并不。 关于我可能在这里失踪的任何指针? 或者KVO不能在Swift和Objective C文件之间工作?
任何帮助,将不胜感激。 谢谢!
相关:http://stackoverflow.com/questions/24092285/ is-key-value-observation-kvo-available-in-swift – kennytm
是myInspect ionRecord'实际上指向你想要观察的代码运行的最后一个对象吗?换句话说:在'addObserver'行放置一个断点,看看'myInspectionRecord'是否为'nil'。如果您正在分配该变量,请务必在设置之前始终取消注册并重新注册。 – DarkDust
顺便说一句,因为你的Swift类是从'UIViewController'(从而'从NSObject')派生的,所以KVO可以正常工作。 – DarkDust