I am creating a button like this inside a method:
UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(0, 0, 100, 50);
[btn setTitle:@"Hello, world!" forState:UIControlStateNormal];
[self.view addSubview:btn];
myButton = btn;
// I am saving the btn reference to this ivar declared on .h as UIButton.
At another point of the code I try to use myButton and it is always nil.
I have tried to retain btn after assigning it to myButton on the original method but myButton is always nil.
self.view is always there. btn is never re开发者_如何学JAVAleased.
Why myButton is nil?
I know I can create the button using alloc, but I am just trying to understand this.
thanks.
UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
here you get an autorelease object of UIButton.
if want to access this button at other places so for this purpose,make it a property and use
UIButton * btn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
or creating by alloc and release it in dealloc .
Edit
in .h
@property (nonatomic,retain) UIButton *myButton;
and in .m
self.myButton=btn;
and release it in dealloc.
OK. You should try the below code
UIButton * btn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
myButton = btn;
It will surely work.
At another point of the code, my guess is that you are using a different MyButton variable than the one you assigned from btn. Perhaps an instance inside a different object, or a local covering the instance, etc.
The btn object should be retained by the addSubView call. But if you remove this button from being a subview, it will be autoreleased.
Because nowhere u have initialized the Button, that is why its giving u nil value.
精彩评论