【问题标题】:How do I keep a UIButton in memory while using ARC?使用 ARC 时如何将 UIButton 保留在内存中?
【发布时间】:2011-10-25 16:56:55
【问题描述】:

我要做的是为每个创建的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]:无法识别的选择器发送到实例 0x6845430

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

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

【问题讨论】:

    标签: objective-c ios memory-management ios5 automatic-ref-counting


    【解决方案1】:

    您的问题在于您使用@selector(buttonHandler)。你的意思是@selector(buttonHandler:)。注意末尾的额外冒号。我喜欢打开“未声明的选择器”(-Wselector)警告来捕捉这种错误。

    【讨论】:

    • 非常感谢,我没有意识到这是必需的,但现在你告诉我这很有意义。很明显,我完全找错了树!
    猜你喜欢
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多