Jakub
Jakub

Reputation: 13860

Strange memory leak? NSURLConnection and NSMutableData object

I have NSURLConnection to download PNG file from URL. Here is the code:

-(void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {
    if (data==nil) { data = [[NSMutableData alloc] initWithCapacity:2048]; }
    [data appendData:incrementalData];
}

-(void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
    [self saveItLocal];
    connection = nil;
    data = nil;
}

-(void)saveItLocal {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *docs = [paths objectAtIndex:0];
    NSString* path =  [docs stringByAppendingFormat:[NSString stringWithFormat:@"/%@.png",self.downloadType]];
    NSData* imageData = [NSData dataWithData:UIImagePNGRepresentation([UIImage imageWithData:data])];
    NSError *writeError = nil;
    [imageData writeToFile:path options:NSDataWritingAtomic error:&writeError];

    if(writeError!=nil) {
        NSLog(@"%@: Error saving image: %@", [self class], [writeError localizedDescription]);
    }

    [[NSNotificationCenter defaultCenter] postNotificationName:@"readyWithGraphics" object:self];

    imageData = nil;

}

enter image description here

Why this object is still living and in memory?

Upvotes: 0

Views: 607

Answers (1)

Alejandro Benito-Santos
Alejandro Benito-Santos

Reputation: 2069

You don't need to explicitly nil the NSURLConnection object, as it will be automatically released by it the framework when it's not needed anymore.

Remove

connection=nil; 

Edit: Sorry, I didn't see you were using an ivar to hold the connection. This is not the way it's usually done. Why are you retaining it along with your object? Just create it and launch it, as I said above, it'll be automatically released when the time comes, but definitely don't make it an ivar unless you have a very good reason for it.

Upvotes: 1

Related Questions