我使用 XIB 创建一个 CustomView:UIView,为 NSInteger 属性加载和 addObserver,如下所示:
//自定义视图.h
@interface CustomView : UIView
@property (nonatomic) NSInteger inputStateControl;
@end
//自定义视图.m
static void *kInputStateControlObservingContext = &kInputStateControlObservingContext;
@implementation CustomView
- (id)init
{
self = [super init];
if (self) {
// Initialization code
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil];
self = [nib objectAtIndex:0];
//
[self commonInit];
}
return self;
}
-(void)commonInit{
[self addObserver:self forKeyPath:@"inputStateControl" options:NSKeyValueObservingOptionOld context:kInputStateControlObservingContext];
}
#pragma mark Observer
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ( context == kInputStateControlObservingContext ) {
NSInteger oldState = [[change objectForKey:NSKeyValueChangeOldKey] integerValue];
if ( oldState != self.inputStateControl ) {
NSLog(@"CONTEXT change %i to %i",oldState,self.inputStateControl);
}
}
else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
-(void)dealloc{
[self removeObserver:self forKeyPath:@"inputStateControl"];
// [self removeObserver:self forKeyPath:@"inputStateControl" context:kInputStateControlObservingContext];
}
@end
如果我在 dealloc 中注释掉 removeObserver,一切正常,这是日志:
CONTEXT change 0 to 2
但是当removeObserver,App崩溃:
*** Terminating app due to uncaught exception 'NSRangeException', reason: 'Cannot remove an observer <Keyboard 0x6a8bcc0> for the key path "inputStateControl" from <Keyboard 0x6a8bcc0> because it is not registered as an observer.'
评论加载 CustomView.xib 时不会崩溃,但与 XIB 无关。我的代码有什么问题?
如何使用自定义 Xib 在 CustomView 中为 NSInteger 属性添加和删除Observer?
提前致谢!
*编辑:我添加我的代码以明确我的问题。请帮忙!
https://github.com/lequysang/github_zip/blob/master/CustomViewKVO.zip