2011-10-06 95 views
0

我正在开发一个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
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 

[connection release];哪里? 例如,在[authURL release];之后放置此行。

+0

更愚蠢的错误!谢谢。 – VansFannel

2

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

+0

谢谢你的回答。你能跟我分享一个关于这样做的例子吗?我在Objective-C编程方面很新颖(正如你所看到的),我不知道该怎么做。 – VansFannel

+1

请参阅NSURLConnection文档的委托部分,以及文档中链接的SimpleURLConnections或LazyTableImages示例代码。 –