I has written following code and then run.
In after, When I touch uibutton, this app is terminated.
I want to know why terminated.
I doubt if autorelease?
Are there anyone who can explicitly explain
why myClass instance is released and
where myClass is released and
the way that myClass can use autorelease?
@interface MyClass : NSObject
- (void)testMethod;
@end
@implementation MyClass{
NSMutableArray *array;
}
- (id)init{
if ((self = [super init])) {
array = [[NSMutableArray alloc] initWithCapacity:0];
}
return self;
}
- (void)dealloc {
[array release];
[super dealloc];
}
- (void)testMethod {
NSLog(@"after init : %@", array);
}
@end
@implementation ViewController {
MyClass *myClass;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
myClass = [[[MyClass alloc] init] autorelease]; <== cause of ternimate?
UIButton *aButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton addTarget:self action:@selector(testArray:) forControlEvents:UIControlEventTouchUpInside];
aButton.frame=CGRectMake(110.0f, 129.0f, 100.0f, 57.0f);
[aButton setTitle:@"title" forState:UIControlStateNormal & UIControlStateHighlighted & UIControlStateSelected];
[self.view addSubview:aButton];
}
- (void)testArray:(id)sender {
[myClass testMethod];
}
@end
Seems that due to
the instance of MyClass is already deallocated when you touch the button. Don’t be lazy – autorelease is not an ultimate ‘solve my memory management problem and make me not have to think’ solution – here you need to use just
then release it manually when needed – probably in your ViewController class’ -dealloc method.