そのような NSInteger プロパティの XIB、load、および addObserver を使用して CustomView:UIView を作成します。
//CustomView.h
@interface CustomView : UIView
@property (nonatomic) NSInteger inputStateControl;
@end
//CustomView.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
しかし、Observer を削除すると、アプリがクラッシュします。
*** 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