帮助解决内存泄漏问题

时间:2011-04-11 16:14:07

标签: objective-c memory-leaks instruments

我创建了一个使用NSURLConnection和KVC从服务器上的plists创建对象的类。仪器说我有一堆内存泄漏来自处理从服务器返回的数据的函数:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    hasOutstandingCall = NO;
    NSError* sError;

    NSDictionary* tmpDict = [NSPropertyListSerialization propertyListWithData:receivedData 
        options:NSPropertyListImmutable
        format:NULL error:&sError];
    self.lastResponse = [ServerResponse new];
    //NSLog(@"server responded: %@",tmpDict);
    [lastResponse setValuesForKeysWithDictionary:tmpDict];
    if(tmpDict.count == 0){
        lastResponse.success = NO;
        lastResponse.errorId = -1;
        lastResponse.errorMessage = @"Couldn't understand server response";
        [[NSNotificationCenter defaultCenter] postNotificationName:@"serverDidRespond" object:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"requestDidFail" object:self];
        NSLog(@"failed to deserialize response");
        NSString* serverMessage = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
        NSLog(@"SERVER SAID: %@",serverMessage);

        [serverMessage release];
        [receivedData release];
        return;
    }

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

    if(lastResponse.success){
        if(lastResponse.resultQuery)
            NSLog(@"%@ response: query with %d rows",lastFName, lastResponse.resultQuery.count);
        else if(lastResponse.resultObject)
            NSLog(@"%@ response: object",lastFName);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"requestDidSucceed" object:self];
    }else{
        NSLog(@"%@ response: ERROR id: %d, message: %@",lastFName, lastResponse.errorId, lastResponse.errorMessage);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"requestDidFail" object:self];
    }

    [receivedData release];
}

仪器说我正在泄漏服务器响应,以及其他一些通过此功能的事情。 “负责任框架”的东西总是指任何最初创建泄露对象的东西,无论如何?我应该只是在寻找这些东西是如何被泄露的,还是我在这个功能中遇到问题?根据我的理解,tempDict,sError在从序列化返回时会自动释放。我将所谓泄露的serverResponse发送到一个在dealloc方法中释放的合成setter,所以我看不出问题是什么。有人有见识吗?

1 个答案:

答案 0 :(得分:2)

self.lastResponse = [ServerResponse new];

这很可能是双重保留,假设lastResponse@property,声明为retain(或您的二传手保留)。

当Instruments识别泄漏时,它会显示项目的分配位置,但这可能不是泄漏的原因。泄漏将始终是一种不平衡的保留,但有时只保留在分配的同一行(就像在这种情况下,显然)。