数组保留问题

时间:2010-06-08 00:07:18

标签: objective-c nsarray retain

对于objective-c来说,这是相当新的,但大部分都是清楚的,但是当涉及到记忆管理时,我会有点短暂。目前我的应用程序所做的是在NSURLConnection期间调用方法-(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

2 个答案:

答案 0 :(得分:2)

是的,newArraymainArray发布时已发布。但这只是在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];
}
相关问题