在开始时我不得不提到我不想因为任何其他原因而继承UIButton。
假设我们有UIButton类别,它与一些格式化方法一起,也观察自身状态变化(启用,突出显示,选中)以调用基于CALayer的花哨按钮格式。
我已经成功设置了观察者,但是当UIButton解除分配时,我也应该将其作为自己的观察者删除。
找到已经可能的解决方案:
1)SFObservers - 为所有应用内NSNotificationCenter和KVO观察员制作全局自动删除器:http://www.merowing.info/2012/03/automatic-removal-of-nsnotificationcenter-or-kvo-observers/
2)将另一个虚拟对象关联到UIButton以获取我在此提到的dealloc:Hooking end of ARC dealloc 及其现成的解决方案:https://github.com/krzysztofzablocki/NSObject-SFExecuteOnDealloc
但是......
问题:是否有更简单的解决方案,例如观察自我dealloc? 也许,我不需要删除自我的KVO(解除分配的对象不会向自己发送任何更改)?
我目前的代码:
#pragma mark - State changes KVO
// Define context
static void * atwContext = &atwContext;
// Method to register for state changes notifications
- (void)atwStartObservingStateChanges {
[self addObserver:self forKeyPath:@"enabled" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:atwContext];
}
// Method to receive all registered state changes notifications
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (context == atwContext) {
if ([@"enabled" isEqualToString:keyPath]) {
NSNumber *newState = [change objectForKey:NSKeyValueChangeNewKey];
NSNumber *oldState = [change objectForKey:NSKeyValueChangeOldKey];
if (oldState && [newState isEqualToNumber:oldState]) {
NSLog(@"Enabled state has not changed");
} else {
NSLog(@"Enabled state has changed to %d", [object isEnabled]);
}
}
}
}