简体   繁体   English

iOS内存泄漏建议

[英]iOS Memory Leak Advice

I'm pretty sure this is causing a leak and I would like some advice. 我很确定这会引起泄漏,我想提出一些建议。 Here's code based on what I'm doing: 这是基于我正在执行的代码:

NSMutableArray* straVideoTitles;

- (void) parseData{
  //stuff
  straVideoTitles = [self getVideoTitle:strData]; //strData contains unparsed data
  //more stuff
}

- (NSMutableArray*) getVideoTitles:(NSString*)strData{
    NSMutableArray *array;
    array = [[NSMutableArray alloc] init];
    //Parse data and populate array
    return array;
}

Based on the fact that I'm allocating space for NSMutableArray and not releasing it, thats a leak right? 基于我为NSMutableArray分配空间而不释放它的事实,那是泄漏吗? How do I tackle this? 我该如何解决? Should I forgo returning a value and assign straVideoTitles inside getVideoTitles then release like: 我应该放弃返回值并在getVideoTitles中分配straVideoTitles,然后按以下方式释放:

- (void) getVideoTitles:(NSString*)strData{
    NSMutableArray *array;
    array = [[NSMutableArray alloc] init];
    //Parse data and populate array
    straVideoTitles = array;
    [array release];
}

or am i going about this all wrong? 还是我要解决所有这些错误? Or is everything fine because I'm releasing straVideoTitles in dalloc? 还是因为我要在dalloc中释放straVideoTitles而使一切正常?

You could change the 您可以更改

return array;

into 进入

return [array autorelease];

Or you could use ARC and just don't care about it anymore. 或者您可以使用ARC,而不再关心它。

Edit: The second approach is possible and does not include a memory leak but the code is less capsulated and therefore less reusable and future prove. 编辑:第二种方法是可能的,并且不包括内存泄漏,但是代码封装较少,因此可重用性较低,并且值得将来证明。

改成

return [array autorelease];

It is good practice to return autorelease objects from methods. 优良作法是从方法中返回自动释放对象。 This is called a deferred release message. 这称为延迟释放消息。

You are relinquishing ownership while allowing the caller of the method to use the returned array before it is deallocated. 您将放弃所有权,同时允许方法的调用者在释放数组之前使用返回的数组。

Your return statement should read: 您的退货声明应为:

return [array autorelease];

For more information on memory management take a look here: 有关内存管理的更多信息,请在这里查看:

Advanced Memory Management Programming Guide 高级内存管理编程指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM