這段代碼爲什麼會產生泄漏?它怎麼能解決?目標C塊內的塊產生泄漏。我該如何解決它?
這是原始呼叫:
NSString * url = @"https://theserverurl/user/login" ;
NSDictionary *parameters = @{@"login":@"[email protected]", @"password":@"encrypted-password"} ;
[[BackEndAPI sharedManager] NSURLSessionOperation: @"POST" url: url parameters: parameters success:^(NSURLRequest *request, NSHTTPURLResponse * response, id responseObject) {
// Success
} failure:^(IDLEngineError *engineError) {
// Failure
}] ;
這是處理NSURL要求單身:
- (NSMutableURLRequest *) NSURLSessionOperation:(NSString *) restOperation
url:(NSString *)url
parameters:(id)parameters
success:(void (^)(NSMutableURLRequest *request, NSHTTPURLResponse * response, id responseObject))success
failure:(void (^)(IDLEngineError *))failure {
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
__weak id weakSelf = self ;
// POST
if ([restOperation isEqualToString:@"POST"]) {
NSError *error;
NSURLSession *session = [NSURLSession sessionWithConfiguration: sessionConfig ];
// Create the request
__block NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: url ] ];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"] ;
request.HTTPMethod = @"POST";
NSData *postData = [NSJSONSerialization dataWithJSONObject: parameters options: 0 error:&error];
[request setHTTPBody:postData];
// Perform operation
NSURLSessionDataTask * task = [session dataTaskWithRequest: request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// This generates a leak!!!!
success(request, nil, nil) ;
}] ;
[task resume] ;
}
return nil ;
}
請看看到GitHub上泄露的應用:
https://github.com/arkyxperience/myleakedapp
在此處查找報告(屏幕截圖)comin克從儀器:
1.不需要__block,這是肯定的。 2.你確定成功塊中沒有任何東西會導致泄漏嗎? 3.請仔細檢查您的「簡化」是否沒有刪除重要的代碼。 –
成功塊應該是直截了當的,不知道這是否是問題所在。我已經將應用程序上傳到GitHub,所以您可以看到簡化沒有刪除有問題的代碼片段,因爲泄漏仍然存在。 – RGML