Reputation: 3165
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
Upvotes: 0
Views: 74
Reputation: 7976
It is the autorelease that is causing an issue.
You should make myClass a property.
@implementation ViewController {
}
@property (nonatomic, retain) MyClass *myClass;
@synthesize myClass
-(void)dealloc
{
[myClass release];
[super dealloc];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.myClass = [[[MyClass alloc] init] autorelease];
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];
}
Upvotes: 0
Reputation:
Seems that due to
myClass = [[[MyClass alloc] init] autorelease];
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
myClass = [[MyClass alloc] init];
then release it manually when needed - probably in your ViewController class' -dealloc method.
Upvotes: 0
Reputation: 410662
myClass = [[[MyClass alloc] init] autorelease];
Probably because you're autoreleasing myClass
. It's an instance variable, so it should be retained (and then released in the class's dealloc
method).
Upvotes: 1