奇怪的内存泄漏? NSURLConnection和NSMutableData对象

时间:2012-11-19 12:33:00

标签: objective-c ios memory-management nsurlconnection

我有NSURLConnection从URL下载PNG文件。这是代码:

-(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

为什么这个物体仍然存在并存在于记忆中?

1 个答案:

答案 0 :(得分:1)

您不需要显式地为NSURLConnection对象添加nil,因为它将在不再需要时由框架自动释放。

删除

connection=nil; 

编辑:对不起,我没有看到你使用ivar来保持连接。这不是通常的方式。为什么要将它与物体一起保留?如上所述,只需创建它并启动它,它会在时机成熟时自动发布,但除非你有充分的理由,否则它绝对不会成为一个ivar。