如何在使用ARC时将UIButton保留在内存中?
问题描述:
我想要做的是为每个UIButton
创建一个函数,并在函数中使用开关来确定其行为。我将按钮上的标签设置为使用开关,但实际上并没有那么远。如何在使用ARC时将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
}
当我点击任何按钮的应用程序抛出一个错误:
-[WatchViewController buttonHandler]: unrecognized selector sent to instance 0x6845430
我认为,这是因为按钮变量被创建,然后因为有它的参考,自动释放通过ARC,所以当函数被调用时它不再存在。不幸的是,我不知道如何保留对内存中每个按钮的引用。
如果我错了(或者我写的东西是不好的练习),随时告诉我,它会帮助我学习!
答
您的问题是您在使用@selector(buttonHandler)
。你的意思是@selector(buttonHandler:)
。注意最后的额外冒号。我喜欢打开“Undeclared Selector”(-Wselector)警告来捕捉这种错误。
非常感谢你,我没有意识到这是必需的,但现在你告诉我这很有道理。很明显,我正在完全错误地吠叫树! – mrh89