在单个类中的多个方法之间共享NSArray内容

时间:2009-08-30 09:49:48

标签: objective-c memory-management

我做错了什么?当我尝试记录数组时,我的代码崩溃了。这是我的班级:

@interface ArrayTestAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    NSArray *array;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) NSArray *array;

-(IBAction)buttonPressed;

@end

@implementation ArrayTestAppDelegate

@synthesize window, array;


- (void)applicationDidFinishLaunching:(UIApplication *)application {    

    array = [NSArray arrayWithObjects:@"Banana", @"Apple", @"Orange", @"Pear", @"Plum", nil];

    [window makeKeyAndVisible];
}

-(IBAction)buttonPressed {

    NSLog(@"%@", array);

}


- (void)dealloc {
    [window release];
    [array release];
    [super dealloc];
}


@end

1 个答案:

答案 0 :(得分:5)

这是Cocoa中常见的内存管理错误。 arrayWithObjects类的NSArray方法返回一个自动释放的对象。当您尝试在buttonPressed方法中记录数组时,该阵列已经被释放并且您将崩溃。修复很简单:

array = [[NSArray alloc] initWithObjects:@"Banana", @"Plum", nil];

或者:

array = [[NSArray arrayWithObjects:@"Banana", @"Plum", nil] retain];

我想第一个更好,第二个例子结尾的保留很容易错过。我建议您在Cocoa中阅读更多有关内存管理的内容。