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

标签 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 方法中出现警报 View 之前。

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

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"]];

堆栈跟踪快照:

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

最佳答案

试试这个:

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

在您的connectionDidFinishLoading:connection:didFailWithError:方法中设置

reportArray = nil

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

关于ios - 如何修复 Objective-C 中的内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31208743/

相关文章:

ios - 苹果设备可以处理 SceneKit 中的多少个顶点

ios - 为什么我不能设置 SKScene(fileNamed :) in GameViewController?

ios - libGDX、RoboVM - 如何编辑 Obj-C 代码?

c - C 中数据被覆盖的内存问题

ios - 访问图库中的连拍模式照片

objective-c - 如何在 AppDelegate 中决定 rootView

iphone - 音乐播放器只播放一首轨道

objective-c - pi 在 OS X 10.8 上已弃用

c++ - 防止多态类中的内存泄漏

ruby-on-rails - Ruby on Rails 循环大量记录时出现内存泄漏; find_each 没有帮助