gpt4 book ai didi

iphone - 从 NSObject 类获取 NSMutableArray 到 UIViewController 类时的内存管理

转载 作者:行者123 更新时间:2023-11-29 13:48:53 24 4
gpt4 key购买 nike

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

@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。您还应该在设置实例变量之前释放它:

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

更好的方法是实际使用您的属性(property):

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

(注意autorelease)

这有利于在您使用它们时触发 KVO-Notifications。

关于iphone - 从 NSObject 类获取 NSMutableArray 到 UIViewController 类时的内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5965680/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com