Well
I have some troubles with initialisation class properties in objective c. I have read a lot information but I didn’t find answer to my question.
So I give example.
1)
//Ex_1.h
@interface Ex_1: UIView {
IBOutlet UIButton *playBut;
}
@property(retain, nonatomic) IBOutlet UIButton *playBut;
-(void) method1;
@end
//Ex_1.m
@implementation Ex_1
@synthesize playBut;
-(id) initWithFrame:(CGRect)frame {
self = [super initWithFrame : frame];
if (self != nil)
playBut = [UIButton buttonWithType:UIButtonTypeRoundedRect]; //retainCount of playBut = 1;
return self;
}
-(void) method1 {
[playBut setTitle:@"pause" forState:UIControlStateNormal];
}
@end
I main Programm first I init object of Ex_1 and then after some times call method1 of this object ([object method1]) and I get runtime error(error tells me that playBut is dealloc, but I think playBut’s retain count = 1).
So I have some questions:
- Is it possible ?
- Why garbage collector dealloces playBut if its retain count = 1?(because I don’t call [playBut release];
- How do I init class properties?
I familar with C++ and actionScript, but I see first time in my life that garbage collector dealloced class property.
I use non ARC.
It is important for me.
Thanks for your attention and answers.
[UIButton buttonWithType:]returns anautoreleasedobject. It will be alive for the lifetime of the scope in which you call it, i.e.initWithFrame:but the autorelease pool can reclaim it after that. You should instead say, in your init selector:Then send this in your
dealloc:Now, if you were to add the
playButas a child to anotherUIView, that view would retain the child and you wouldn’t need to, as long as you only use it during the lifetime of the super view. This is a normal pattern. You could go further and assign atagto playBut then use viewWithTag: to find yourUIButtonwhen you need it.