2010-12-08 39 views
1

我的方法里创建这样一个按钮:iPhone - 方法之外的零按钮?

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. 

在我尝试使用myButton的代码的另一点,它始终是零。

我试图在原来的方法将其分配给myButton的后保留BTN但myButton为始终为零。

self.view始终存在。 btn从未发布。

为什么myButton是零?

我知道我可以创建一个使用ALLOC按钮,但我只是想了解这一点。

谢谢。

+0

您可能正在寻找self.myButton = btn; – Rog 2010-12-08 06:31:32

回答

1
UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 

这里你会得到一个UIButton的autorelease对象。

如果想在别的地方可以访问此按钮,以便为这个目的,使之成为性能和页头使用

UIButton * btn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain]; 

或 创建和dealloc中释放

编辑

在.H

@property (nonatomic,retain) UIButton *myButton; 

和.M

self.myButton=btn; 

和dealloc中释放出来。

+0

好的,但不会保留,因为它被添加为self.view子视图? – SpaceDog 2010-12-08 06:32:26

-1

因为无处u必须初始化按钮,这就是为什么它给ü零值。

+0

该按钮初始化为`UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];`为您创建一个新按钮。 – rckoenes 2012-08-17 08:19:10

0

好的。你应该试试下面的代码

的UIButton *干训局= [[UIButton的buttonWithType:UIButtonTypeRoundedRect]保留];

myButton = btn;

它肯定会奏效。

0

在代码的另一点,我的猜测是,你正在使用比你从BTN分配一个不同的变量myButton的。也许一个不同的对象,或一个本地覆盖的情况下,等

的BTN对象内部的实例应该由addSubView呼叫被保留。但是如果你从子视图中删除这个按钮,它将被自动释放。