IOS 6.1
我们注意到,当我们为不存在的键值对获得 removeObserver 异常时,具有 KVP 获取的类和 removeObserver 调用中的额外保留计数。
以下是一些证明这一点的测试代码。还有一个桥接版本可以解决这个问题。
欢迎任何意见......
#import "ViewController.h"
#import "ClassA.h"
@interface ViewController ()
@property (strong, nonatomic) ClassA* classA;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"radarOn"])
{
NSLog(@"--- here in radaron");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Here" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
}
- (IBAction)CreateClassAAction:(id)sender
{
self.classA = [[ClassA alloc] init];
}
- (IBAction)SendNotificationAction:(id)sender
{
self.classA.radarOn = ! self.classA.radarOn;
}
- (IBAction)ClearKVPAction:(id)sender
{
@try
{
[self.classA removeObserver:self forKeyPath:@"radarOn"];
}
@catch (NSException *exception)
{
NSString *s = [NSString stringWithFormat:@"Exception ClassA Retain Count %ld %@", CFGetRetainCount((__bridge CFTypeRef)(self.classA)), exception.description];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:s delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
// this will let the class release
// CFBridgingRelease((__bridge CFTypeRef)(self.classA));
}
}
- (IBAction)AddKVPAction:(id)sender
{
[self.classA addObserver:self forKeyPath:@"radarOn" options:NSKeyValueObservingOptionNew context:nil];
}
@end
#import <Foundation/Foundation.h>
@interface ClassA : NSObject
@property (nonatomic, assign) BOOL radarOn;
@end
#import "ClassA.h"
@implementation ClassA
- (void) dealloc
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"ClassA Dealloc" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
@end