如何修复Objective-C中的内存泄漏?

时间:2015-07-03 14:04:37

标签: ios objective-c memory-leaks instruments

我构建了一个简单的应用程序,可以从HockeyApp获取报告。但是,当我使用内存泄漏工具运行应用程序时,它表明在执行getReport操作时存在内存泄漏。我无法理解乐器中显示的所有信息。

这是导致内存泄漏的按钮操作方法:

- (IBAction)getReports:(id)sender {

//initialize url that is going to be fetched.
NSURL *url = [NSURL URLWithString:@"https://rink.hockeyapp.net/api/2/apps/APP_ID/crash_reasons"];

//initialize a request from url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:tokenReceived forHTTPHeaderField:@"X-HockeyAppToken"];

[request setHTTPMethod:@"GET"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

//initialize a connection from request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
self.getReportConnection = connection;

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data{

    if (connection==getReportConnection) {

     [self.receivedData appendData:data];

     NSLog(@"data is %@",data);

    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSError *e = nil;
    NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];

    NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error: &e];
    NSLog(@"login json is %@",JSON);
     NSLog(@"reason json is %@",JSON[@"reason"]);

    [JSON[@"crash_reasons"] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {


        [reportArray addObject:obj[@"reason"]];
         NSLog(@"index = %lu, Object For title Key = %@", (unsigned long)idx, obj[@"reason"]);
    }];

    NSError *error = nil;
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData
                                                         options:kNilOptions error:&error];

    if (error != nil) {
        NSLog(@"Error parsing JSON.");
    }
    else {
        NSLog(@"Array: %@,array count is %d", jsonArray,jsonArray.count);
    }

   // [reportArray addObject:[jsonArray objectAtIndex:0]];

    if (JSON!=NULL) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Reports succesfully retrieved" message:@"" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [alert show];
    }

       }
}

 // This method receives the error report in case of connection is not made to server.
 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

UIAlertView *errorAlert=[[UIAlertView alloc]initWithTitle:@"Wrong Login" message:nil delegate:self cancelButtonTitle:@"ok" otherButtonTitles: nil];
[errorAlert show];
NSLog(@"error is %@",error);
}

// This method is used to process the data after connection has made successfully.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

}

我发现内存泄漏发生在警告视图出现在didRecieveData方法之前。

以下是显示内存泄漏的内存泄漏工具的屏幕截图:

enter image description here

我无法理解代码的哪一部分导致内存泄漏。谁能告诉我如何识别导致泄漏仪器泄漏内存的代码部分?

编辑:当我在模拟器上运行应用程序时,仪器没有显示任何内存泄漏:

以下是截图: enter image description here

再次当我在设备上运行应用程序时,仪器显示内存泄漏: enter image description here

我查看了泄漏部分,发现NSmutableArray导致泄漏: enter image description here enter image description here

我的代码中只使用了一个NSMutableArray。我在.h文件中声明了它:

@property (nonatomic,strong) NSMutableArray *reportArray;

并将其分配到viewDidLoad

reportArray=[[NSMutableArray alloc]init];

并将其加载到didRecieveData

 [reportArray addObject:obj[@"reason"]];

Stacktrace快照:

enter image description here enter image description here enter image description here

2 个答案:

答案 0 :(得分:2)

试试这个:

reportArray = [[[NSMutableArray alloc] init] autorelease];

在您的connectionDidFinishLoading:connection:didFailWithError:方法集

reportArray = nil

最后在项目>构建阶段>编译源添加-fno-objc-arc作为此文件的编译器标志 (已编辑,对不起)。然后再次单击产品菜单>分析(命令+ shift + B)并检查是否仍然发生内存泄漏。

答案 1 :(得分:0)

可能是Apple的漏洞 - 看起来它来自UIAlertView / UIAlertConnection。您可以尝试使用UIAlertConnection实现警报并查看它是否消失 - Apple可能没有对后端兼容的UIAlertView实现进行过多次测试。

它不会出现在泄漏中,但请注意NSURLConnection会保留其委托,并且在您的情况下,您的代理人会保留它看起来像NSURLConnection。如果我没有弄错的话,这应该是一个保留循环。当连接完成或失败时,一定要打破它(没有代理,或者控制器上没有连接)。