-(void)connectionDidFinishLoading:(NSURLConnection *)connection
时我输入一个方法来解析一些数据,将它放入一个数组,然后返回该数组。但是我不确定这是否是最好的方法,因为我没有在自定义方法中释放内存中的数组(method1,请参阅附带的代码)
下面是一个小脚本,可以更好地展示我在做什么
.h文件
#import <UIKit/UIKit.h>
@interface memoryRetainTestViewController : UIViewController {
NSArray *mainArray;
}
@property (nonatomic, retain) NSArray *mainArray;
@end
.m文件
#import "memoryRetainTestViewController.h"
@implementation memoryRetainTestViewController
@synthesize mainArray;
// this would be the parsing method
-(NSArray*)method1
{
// ???: by not release this, is that bad. Or does it get released with mainArray
NSArray *newArray = [[NSArray alloc] init];
newArray = [NSArray arrayWithObjects:@"apple",@"orange", @"grapes", "peach", nil];
return newArray;
}
// this method is actually
// -(void)connectionDidFinishLoading:(NSURLConnection *)connection
-(void)method2
{
mainArray = [self method1];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
mainArray = nil;
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[mainArray release];
[super dealloc];
}
@end
答案 0 :(得分:2)
是的,newArray
在mainArray
发布时已发布。但这只是在method2
被调用一次。
我们正在谈论参考文献,如果你有
newArray = something
mainArray = newArray
[mainArray release]
两个变量仅引用NSArray*
。那么在你的情况下,newArray
只是一个本地,所以没有问题。
如果您拨打method2
两次,则会出现问题:
newArray = something
mainArray = newArray
newArray = something2
mainArray = newArray <- old reference is lost
[mainArray release] <- just something2 is released
要避免此问题,您应确保在使用其他对象覆盖引用之前释放mainArray
。
答案 1 :(得分:2)
您的-method1
首先创建一个新数组,然后用新数组覆盖它:
NSArray *newArray = [[NSArray alloc] init]; // first array, retained
newArray = [NSArray arrayWithObjects:...]; // second array, auto-released,
// pointer to first one lost
第一个阵列只是泄露在这里。您还泄漏了存储在ivar中的数组,只需使用合成的setter来避免它 - 它会为您保留和释放。
如果您还没有这样做,请阅读C {的Memory Management Guide。
更好的版本:
- (NSArray *)method1 {
NSArray *newArray = [NSArray arrayWithObjects:...];
return newArray;
}
- (void)method2 {
self.mainArray = [self method1];
}