views:

326

answers:

2

My app has an NSOperation class called ServerRequest that handles networking tasks. According to instruments, it is leaking like crazy. Additionally, instruments says the code that builds the request is leaking, even though that is not an NSOperation. But I have followed Apple's advice in terms of setting up an autorelease pool, so I don't understand what could be the matter. Can anyone help?

A portion of my code is below:

-(void) main {
 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 self.data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];  // lots of leakage here
 [self postResult]; // leakage here too
 [pool release];
}

and the postResult method (which is not leaking):

-(void) postResult {
// error handling code here

 if (![self isCancelled])
 {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  NSMutableDictionary *resultDictionary = [[NSMutableDictionary alloc]init];
  if (self.data!=nil)
   [resultDictionary setObject:self.data forKey:kDataKey];
  if (self.response!=nil)
   [resultDictionary setObject:self.response forKey:kResponseKey];
  if (self.error!=nil)
   [resultDictionary setObject:self.error forKey:kErrorKey];
  NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  NSNotification *notification = [NSNotification notificationWithName: kDownloadCompleteName object: self userInfo: resultDictionary];
  [resultDictionary release];
  [center postNotification: notification];

  [pool drain];
 }
}

Lastly, dealloc:

- (void) dealloc {
 self.request = nil;
 self.data = nil;
 self.mutableData = nil;
 if (!self.error)
  self.error = nil;
 if (!self.response)
  self.response = nil;
 [super dealloc];
}
A: 

Some recommend avoiding the self.var = nil setter approach to releasing variables in the -dealloc deconstructor.

Have you tried the old tried-and-true [var release], var = nil approach?

Alex Reynolds
Yes. It's still the case that if I release it, the program crashes, saying that I am sending a message to a deallocated object. But if I don't release it, instruments shows a leak.
William Jockusch
what's wrong with self.var = nil ?
DenNukem
I'll see if I can find the blog posting that discusses why this is a bad idea. Maybe someone who knows the post I'm referring to can also post if they find it first.
Alex Reynolds
A: 

I have the same problem with an NSMutableData object in an NSOperation. Note that several other instance variables (NSString's) release fine.

Adding NSZombieDetection support gives this additional information:

* -[NSConcreteMutableData release]: message sent to deallocated instance 0xd676fd0

Is there a way to set a breakpoint on NSConcreteMutableData's dealloc function, to see where it has been deallocated the first time ?

Colin