【问题标题】:Memorymanagement when getting a NSMutableArray from NSObject class to UIViewController class从 NSObject 类到 UIViewController 类获取 NSMutableArray 时的内存管理
【发布时间】:2011-05-11 14:14:13
【问题描述】:

我遇到以下代码泄漏内存的问题...

@property (nonatomic, retain) NSMutableArray *childrensArray;


-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

NSLog(@"Connection finished loading.");  
// Dismiss the network indicator when connection finished loading
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

// Parse the responseData of json objects retrieved from the service
SBJSON *parser = [[SBJSON alloc] init];

NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *jsonData = [parser objectWithString:jsonString error:nil];
childrensArray = [jsonData objectForKey:@"Children"];

// Callback to AttendanceReportViewController that the responseData finished loading
[attendanceReportViewController loadChildren];

[connection release];
[responseData release];
[jsonString release];
[parser release]; 
}  

在 viewController 中,以下内容也会泄漏内存...

@property (nonatomic, retain) NSMutableArray *childrensArray;


- (void)loadChildren {

// Retrieve a array with dictionaries of children from ServiceGetChildren
self.childrensArray = [[serviceGetChildren.childrensArray copy] autorelease];   

int total = [childrensArray count];
totalLabel.text = [NSString stringWithFormat:@"%d", total]; 

[theTableView reloadData];
}   

【问题讨论】:

  • 请您清理一下您发布的代码。
  • 我只是说,但是.. 在你的泄密线之后(childrensArray = [serviceGetChildren.childrensArray copy]; 你有一个{ 而不是}。另外,我希望这不是完全复制全部粘贴一次,但部分复制粘贴,对吧?因为如果布局完全一样,还有更多..嗯,事情,错了。
  • @toto 是的,当然很抱歉。现在可能更容易阅读。

标签: iphone objective-c ios memory-leaks


【解决方案1】:

只有在实例被释放时才释放childrensArray。您还应该在设置实例变量之前释放它:

- (void)loadChildren {
    // Retrieve a array with dictionaries of children from ServiceGetChildren 
    [childrensArray release];
    childrensArray = [serviceGetChildren.childrensArray copy]; 
}

更好的方法是实际使用您的财产:

- (void)loadChildren {
    // Retrieve a array with dictionaries of children from ServiceGetChildren 
    self.childrensArray = [[serviceGetChildren.childrensArray copy] autorelease]; 
}

(注意autorelease

这有利于在您使用 KVO 通知时触发它们。

【讨论】:

  • 另一个问题是childrensArray = [jsonData objectForKey:@"Children"];,它覆盖了childrensArray实例变量而不释放它。应使用临时变量。
  • 好的,如果我这样做 self.childrensArray = [[serviceGetChildren.childrensArray copy] autorelease];我不需要在dealloc中释放它?
  • @Tony 好的,但是如果我使用临时变量,我如何从 viewController 中检索它?我还设置它的属性吗?或者你是什么意思?
  • @Silversnail 好吧,我没有意识到这是两个不同的类。它应该是self.childrensArray = [jsonData objectForKey:@"Children"],以便您释放之前指向的任何childsArray 并保留新值。在您的 viewController 中,您拥有的更新代码很好,即 self.childrensArray = [[serviceGetChildren.childrensArray copy] autorelease],但它应该是 mutableCopy(您正在分配给 NSMutableArray)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-10
  • 1970-01-01
  • 2011-09-06
  • 2010-10-02
  • 2011-02-19
  • 2011-07-01
相关资源
最近更新 更多