views:

73

answers:

1

What am I doing wrong? My code crashes when I try to log the array. Here is my class:

@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
+4  A: 

This is a common memory management error in Cocoa. The arrayWithObjects method of the NSArray class returns an autoreleased object. By the time you try to log the array in the buttonPressed method, the array has already been released and you get a crash. The fix is easy:

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

Or:

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

I guess the first one is better, the retain on the end of the second example is easy to miss. I would suggest that you read some more on memory management in Cocoa.

zoul