| There are three related mistakes contributing to this bug: 1. The test is depending on dealloc being done eagerly. 2. The Attempt class puts unsubscribe code in its dealloc method. 3. The Attempt class does not force callers to control its lifetime. I'll go into more depth on these. 1. Cleanup is often deferred. Dealloc may only run AFTER the test instead of DURING the loop (e.g. I think NSArray defers releasing its items in some cases). Tests that depend on cleanup occurring eagerly, without explicitly waiting or forcing it, are brittle. Given that Attempt uses dealloc to unsubscribe, and we are testing that it unsubscribed, we should at the very least allocate it in an autoreleasepool that ends before we test that it unsubscribed. 2. Putting unsubscribe code in dealloc is a great way to upgrade minor memory leak bugs into major behavior bugs. The article gives fantastic examples of this happening many different ways. Don't rely on the object happening to go out of scope at the right time. If your object's lifetime is controlling whether or not side effects occur, that's a bad situation to be in. 3. Someone has to be responsible for when unsubscribing happens (since we took it away from dealloc), and the someone most in a position to know when is the caller. We should force them to tell us our subscription lifetime. I like to control lifetimes with cancellation tokens [1], so I'd write the attempt class like this: @implementation Attempt
-(instancetype) initUntil:(TOCCancelToken*)untilCancelledToken {
if (self = [super init]) {
id cleanupObj = ... addObserverForName stuff from Attempt1 ...
[untilCancelledToken whenCancelledDo:^{
[NSNotificationCenter.defaultCenter removeObserver:cleanupObj];
}];
}
return self;
}
- (void)setLocalCounter:(int)localCounter { ... }
- (int)localCounter { ... }
@end
Here's what the test should look like: -(void)testExample {
for(int i =0; i < 5; i++) {
TOCCancelTokenSource* c = [TOCCancelTokenSource new];
Attempt *a = [[Attempt alloc] initUntil:c.token];
[NSNotificationCenter.defaultCenter postNotificationName:notificationName object:nil];
[c cancel];
XCTAssertEqual(counter, i+1, @"Unexpected value for counter.");
XCTAssertEqual(1, attempt1.localCounter, @"Unexpected value for localCounter.");
}
}
Hopefully I got that right. I don't have a mac nearby to test it out at the moment, and I've never used NSNotificationCenter before.1: http://twistedoakstudios.com/blog/Post7391_cancellation-toke... |
I dislike that receiving the notification mutates global state though. I can't clearly articulate it, but that's why I think the caller should have explicit control over when the behavior is active. I think notification subscriptions that last for the lifetime of the object should probably be related to the object's internal state.
Finally, I went to the clang docs regarding timing of dealloc, and as I read it, they shoot for immediate deallocation, but let it slide for local variables: