Dot*_*ash 2 memory-management objective-c
我究竟做错了什么?当我尝试记录数组时,我的代码崩溃了.这是我的班级:
@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
Run Code Online (Sandbox Code Playgroud)
这是Cocoa中常见的内存管理错误.该类的arrayWithObjects
方法NSArray
返回一个自动释放的对象.当您尝试在buttonPressed
方法中记录数组时,该数组已经被释放并且您将崩溃.修复很简单:
array = [[NSArray alloc] initWithObjects:@"Banana", @"Plum", nil];
Run Code Online (Sandbox Code Playgroud)
要么:
array = [[NSArray arrayWithObjects:@"Banana", @"Plum", nil] retain];
Run Code Online (Sandbox Code Playgroud)
我想第一个更好,第二个例子结束时的保留很容易错过.我建议你在Cocoa中阅读更多关于内存管理的内容.
归档时间: |
|
查看次数: |
196 次 |
最近记录: |