Objective c 在ARC中未调用UIButton选择器

Objective c 在ARC中未调用UIButton选择器,objective-c,uibutton,automatic-ref-counting,selector,Objective C,Uibutton,Automatic Ref Counting,Selector,我有两个类,视图和视图控制器。视图创建一个按钮,如下所示: _button = [[UIButton alloc] initWithFrame:CGRectMake(50, 0, buttonImage.size.width, buttonImage.size.height)]; [_button setImage:buttonImage forState:UIControlStateNormal]; [_button setImage:[UIImage imageNamed:@"btn_lea

我有两个类,
视图
视图控制器。
视图创建一个按钮,如下所示:

_button = [[UIButton alloc] initWithFrame:CGRectMake(50, 0, buttonImage.size.width, buttonImage.size.height)];
[_button setImage:buttonImage forState:UIControlStateNormal];
[_button setImage:[UIImage imageNamed:@"btn_learn_focus_pad"] forState:UIControlEventTouchUpInside];
[_button addTarget:self action:nil forControlEvents:UIControlEventTouchUpInside];
[_someView addSubview:_button];
[view.button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
ViewController
中,在
loadView
中实例化视图后,我向is添加了一个选择器,如下所示:

_button = [[UIButton alloc] initWithFrame:CGRectMake(50, 0, buttonImage.size.width, buttonImage.size.height)];
[_button setImage:buttonImage forState:UIControlStateNormal];
[_button setImage:[UIImage imageNamed:@"btn_learn_focus_pad"] forState:UIControlEventTouchUpInside];
[_button addTarget:self action:nil forControlEvents:UIControlEventTouchUpInside];
[_someView addSubview:_button];
[view.button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
没有调用选择器。我试图在
ViewController
按钮的位置中
NSLog
,它打印出一个零。我怀疑ARC正在释放按钮<代码>\按钮但是,它是一个
指针(
@属性
)。所以我不知道为什么会这样


如何解决这个问题?

您没有使用由属性合成生成的适当的getter/setter方法。如果仅将第一行更改为:

self.button = [[UIButton alloc] initWithFrame:CGRectMake(50, 0, buttonImage.size.width, buttonImage.size.height)];

它将正确地保留指针

Oh。。那么,为什么直接访问ivar不能正确保留指针呢?实际上,同样的问题仍然存在。我用
self.button
替换了所有
\u按钮
,但它仍然不起作用无论您是否意识到,您都在使用自动生成的
setButton
方法。当您只需执行
\u按钮=[[UIButton alloc]init]它只是将地址设置为指针变量,并不会自动增加所需按钮的保留计数created@Nayefc您可能没有保留按钮的父视图或视图本身。如果没有看到更多的代码,我真的无法判断问题是什么。我知道了-有另一个问题,但你的答案也是正确的(我有两个问题)。谢谢为什么要将
nil
作为
-addTarget:action:forControlEvents:
的选择器传递?这是无效的,我很惊讶它没有抛出参数断言。另外,您正在为无效状态设置映像<代码>UIControlEventTouchUpInside
为1<代码>UIControlEventTouchUpInside有效。当你按按钮的时候。