-[NSURLConnection cancel] doesn't release its delegate?
-[NSURLConnection cancel] doesn't release its delegate?
- Subject: -[NSURLConnection cancel] doesn't release its delegate?
- From: "Jonathan del Strother" <email@hidden>
- Date: Thu, 18 Dec 2008 17:57:06 +0000
Heya,
I ran into a memory leak recently that I finally managed to track down
to NSURLConnection retaining its delegate.
It appears that cancelling an NSURLConnection won't actually release
its delegate until the next time around the run loop. Normally this
is fine, but I was running on a separate thread with its own run loop,
and I was just cancelling the connection & immediately exiting the
thread.
Is this a bug, undocumented feature, or am I missing something?
A teeny sample program demonstrating the problem appears below.
-Jonathan
#import <Foundation/Foundation.h>
#include <libkern/OSAtomic.h>
static int32_t factoryCount=0;
@interface ConnectionFactory : NSObject { }
@end
@implementation ConnectionFactory
-(id)init {
if (self = [super init]) {
OSAtomicIncrement32Barrier(&factoryCount);
NSLog(@"Made new connection factory : we now have %lu instances",
factoryCount);
[NSThread detachNewThreadSelector:@selector(startConnection)
toTarget:self withObject:nil];
}
return self;
}
-(void)dealloc {
[super dealloc];
OSAtomicDecrement32Barrier(&factoryCount);
NSLog(@"Killing connection factory : %lu instances remaining ", factoryCount);
}
// This all occurs on a secondary thread
-(void)startConnection {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSLog(@"Starting connection on secondary thread, NSURLConnection will
retain the connection factory");
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:@"http://google.com"]];
NSURLConnection* connection = [[NSURLConnection alloc]
initWithRequest:request delegate:self];
NSLog(@"Cancelling connection");
[connection cancel];
[connection release];
// [[NSRunLoop currentRunLoop] runUntilDate:[NSDate date]]; //
Uncommenting this seems to allow NSURLConnection to release its
delegate.
NSLog(@"Secondary thread is done");
[pool release];
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
[[[ConnectionFactory alloc] init] release];
[pool drain];
sleep(5);
pool = [[NSAutoreleasePool alloc] init];
NSCAssert(factoryCount==0, @"By this point our connection factory
really should have been dealloced");
NSLog(@"Yay, looks like our factory was properly released");
[pool drain];
return 0;
}
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden