使用ARC时如何将UIButton保留在内存中?

mrh*_*h89 2 memory-management objective-c ios ios5 automatic-ref-counting

我要做的是为每个UIButton创建的函数设置一个函数,并使用函数内部的开关来确定其行为.我在按钮上设置标签以使用开关,但它实际上并没有那么远.

for var(int i = 0; i < numResults; i++)
{
   UIButton* button = [[UIButton] alloc] initWithFrame:CGRectMake(0,(i*55)+10,320,50)];
   [buttton setTag:i];
   [button addTarget:self action:@selector(buttonHandler) forControlEvents:UIControlEventTouchUpInside];
   [self.view addSubview:button];
}

   ...

-(void) buttonHandler:(id)sender
{
    //Handle the button press
}
Run Code Online (Sandbox Code Playgroud)

当我点击任何按钮时,应用程序会抛出一个错误:

- [WatchViewController buttonHandler]:无法识别的选择器发送到实例0x6845430

我相信这是因为创建了按钮变量,然后由于没有对它的引用,由ARC自动释放,因此在调用该函数时它不再存在.不幸的是,我不知道如何保持对内存中每个按钮的引用.

如果我错了(或者我写的任何东西都是不好的做法),请随时告诉我 - 它会帮助我学习!

Rob*_*ier 6

你的问题在于你的使用@selector(buttonHandler).你的意思@selector(buttonHandler:).注意最后的额外冒号.我喜欢打开"未声明的选择器"(-Wselector)警告来捕捉这种错误.