2011-10-06 109 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示例代碼。 –