Share NSArray Content between multiple methods in one class
What am I doing wrong? My code fails when I try to register an 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
+2
source to share
1 answer
This is a common memory management bug in Cocoa. The arrayWithObjects
class method NSArray
returns an auto-implementing object. By the time you try to register the array with the method buttonPressed
, the array has already been released and you will get a crash. The fix is โโeasy:
array = [[NSArray alloc] initWithObjects:@"Banana", @"Plum", nil];
Or:
array = [[NSArray arrayWithObjects:@"Banana", @"Plum", nil] retain];
I think the first is better, keeping it at the end of the second example is easy to miss. I would encourage you to read a little more about memory management in Cocoa.
+5
source to share