I'm developing an iPhone application. I have the following method:
- (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];
}
I'm getting a: potential leak on an object allocated on line 52 and stored into 'connection'
.
Dealloc method for this class is:
- (void) dealloc {
NSLog(@"TokenGenerator - dealloc");
[responseData release];
[localApiKey release];
[super dealloc];
}
And interface declaration is:
@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
How can I fix this problem? May I create a copy to that object, and then assign it to responseData?
Where is
[connection release];
? Put this line after[authURL release];
for example.Your code starts an asynchronous request, but you try to access the returned data and then intend to release the connection immediately. You need to implement the delegate methods, which you presumably have in order to be able to read the returned data, and release the connection in the finished and failed delegate methods. The code you have will work with fast network connections (possibly), but will fail in the real world.