I'm using an NSThread as follows
NSThread * thread = [[NSThread alloc] initWithTarget:object selector:@selector(bg) object:nil];
[thread start];
Later on I want to stop the thread and deallocate object as follows:
[thread cancel];
[object release];
This seems to work ok. However, when I look at the leaks tool I'm seeing some mysterious leaks not coming anywhere from my code (an empty NSArray). When I looked at the malloc history I see that the NSArray is being allocated in a "willChangeValueForKey" method that is being called ultimately from my [object dealloc]. It happens to be setting a delegate to nil. That delegate is being observed (therefore the willChangeValueForKey?). The [object dealloc] is called from an [NSThread exit].
My guess was that this is because the [thread cancel] doesn't spin down the thread right away (it's in a different thread after all). And then we release object on the main thread. This leaves its retainCount at 1. Then the NSThread will release object when it does actually spin down. It appears that this causes the leak. I tried this quick change to validate my assumption:
[thread cancel];
[NSThread sleepForTimeInterval:1];
// This makes it wait until the thread releases [object]
[object release];
Question: why is it unsafe to let the NSThread deallocate my object? Does it have to do with the observer code being unsafe in dealloc?