保留时可能发生泄漏

时间:2011-10-06 09:17:36

标签: iphone objective-c memory-leaks

我正在开发一个iPhone应用程序。我有以下方法:

- (void)generateTokenWithUserId: (NSString *)uniqueId {

    NSLog(@"TokenGenerator - generateTokenWithUserId: '%@'", uniqueId);

    NSString *myMD5String = [Utilities returnMD5Hash:uniqueId];

    // Create the request.
    NSMutableString *authURL = [[NSMutableString alloc] initWithString:CLOUDMADE_AUTH];
    [authURL appendString: localApiKey];
    [authURL appendString: USER_ID];
    [authURL appendString: myMD5String];

    NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:authURL]
                                                            cachePolicy: NSURLRequestUseProtocolCachePolicy
                                                        timeoutInterval: 60.0];
    [theRequest setHTTPMethod: @"POST"];

    NSLog(@"TokenGenerator URL - '%@'", authURL);

    // create the connection with the request
    // and start loading the data
    //NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if (connection) {
        // Create the NSMutableData to hold the received data.
        // receivedData is an instance variable declared elsewhere.
        responseData = [[NSMutableData data] retain];
    } else {
        // Inform the user that the connection failed.
    }

    [authURL release];
}

我得到了:potential leak on an object allocated on line 52 and stored into 'connection'

此类的Dealloc方法是:

- (void) dealloc {

    NSLog(@"TokenGenerator - dealloc");

    [responseData release];
    [localApiKey release];

    [super dealloc];
}

接口声明是:

@class TokenGenerator;

@protocol TokenGeneratorDelegate <NSObject>

- (void)tokenGeneratorDidFinishGeneration:(TokenGenerator *)tokenGenerator token:(NSString *)tokenGenerated;

@end


@interface TokenGenerator : NSObject {

    NSString *localApiKey;
    id<TokenGeneratorDelegate> delegate;
    NSMutableData *responseData;
}

@property (nonatomic, assign) id<TokenGeneratorDelegate>delegate;

- (id) initWithApikey:(NSString*) apiKey delegate:(id)anObject;
- (void)generateTokenWithUserId: (NSString *)uniqueId;

@end

如何解决此问题?我可以为该对象创建一个副本,然后将其分配给responseData吗?

2 个答案:

答案 0 :(得分:2)

 NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

[connection release];在哪里? 例如,在[authURL release];之后加上这一行。

答案 1 :(得分:2)

您的代码启动异步请求,但您尝试访问返回的数据,然后打算立即释放连接。您需要实现委托方法,这些方法可能是为了能够读取返回的数据,并在已完成和失败的委托方法中释放连接。您拥有的代码将使用快速网络连接(可能),但在现实世界中将失败。