A question mainly to Foundation developers. The example below demonstrates how leaking a KVO observer causes crash on a seemingly unrelated operation. On one hand this is of course programmer's bug, on the other hand one of our devs has just spent a lot of time figuring out what is wrong with "unrelatedGoodProperty" in her code. Do you think it is something that can be improved? Or documented?
@interface Spectacular : NSObject
@property (copy) NSString* propertyLeakingObservers;
@property (copy) NSString* unrelatedGoodProperty;
@end
@implementation Spectacular
@end
@interface LeakedObserver : NSObject
@end
@implementation LeakedObserver
@end
@interface Observer : NSObject
@end
@implementation Observer
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context;
{
NSLog(@"Observing %@ of %@", keyPath, object);
}
@end
- (void) applicationDidFinishLaunching:(NSNotification *)aNotification;
{
Spectacular* spectacular = [Spectacular new];
@autoreleasepool {
LeakedObserver* observerLeak = [LeakedObserver new];
[spectacular addObserver:observerLeak forKeyPath:@"propertyLeakingObservers" options:0 context:0];
}
Observer* observer2 = [Observer new];
[spectacular addObserver:observer2 forKeyPath:@"unrelatedGoodProperty" options:0 context:0];
spectacular.unrelatedGoodProperty = @"boop"; // *** -[LeakedObserver retain]: message sent to deallocated instance 0x6040000013d0
[spectacular removeObserver:observer2 forKeyPath:@"unrelatedGoodProperty" context:0];
}