Memory bad acces: Questions with releases, protocols and delegates
I have a little question with memory management is iOS...
Well I define a own view that have one protocol. In other class, I create an instance of the other class, I add the view to other view and then, I try to release de instance. The problem appear when I call to the method of the protocol because I receive a BAD_ACCS error. It is something like this:
- (void)viewDidLoad{
Class1 *c1 = [[Class1 alloc]init];
[c1 setDelegate:self];
[self.view addSubview:c1.view];
[c1 release];
}
- (void)methodOfPro开发者_StackOverflowtocolClass1 {
NSLog(@"c1 method called")
}
The Class1 have one button and when I press it I call to methodOfProtoclClass1 and makes the error. Does anyone know how to release this object?
Thanks,
David
You are overreleasing c1 here...
- (void)viewDidLoad{
Class1 *c1 = [[Class1 alloc]init]; //allocates Class1 instance with +1 ref count
[c1 setDelegate:self];
[self.view addSubview:c1.view];
[c1 release]; //releases c1, ref count goes to 0 and the memory is reclaimed later
}
therefore you get bad access, you instance of c1 is gone and not valid by the end of your viewDidLoad method
You don't have to release c1, instead you must retain it! addSubview does not retain c1 instance, it retains only its view! If you refer to c1 later you will get a bad access
精彩评论