使用colorWithRed时,iOS应用程式崩溃:green:blue:alpha [英] iOS App crashes when using colorWithRed:green:blue:alpha

查看:218
本文介绍了使用colorWithRed时,iOS应用程式崩溃:green:blue:alpha的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的iOS应用程序中有一个 UIControl 子类(我使用的是iOS 4.3),子类的一部分是一个名为setButtonColor:(UIColor)bc 。每当我从我的代码调用这个方法,它工作正常...但只有当我使用内置的颜色,如greenColor或redColor。如果我使用 colorWithRed:green:blue:alpha 来使我自己的颜色在控制台中与此消息崩溃:

I have a UIControl subclass in my iOS App (I'm using iOS 4.3), and part of the subclass is a method called "setButtonColor:(UIColor)bc". Whenever I call this method from my code, it works fine...but only if I use a built-in color like greenColor or redColor. If I use "colorWithRed:green:blue:alpha," to make my own color it crashes with this message in the console:

-[UIDeviceRGBColor set]: message sent to deallocated instance 0x4e61560

这里是setButtonColor:方法:

Here's the setButtonColor: method:

-(void)setButtonColor:(UIColor *)bc{
    buttonColor = bc;
    [self setNeedsDisplay];
}



如果我删除 setNeedsDisplay ,它不会崩溃,但按钮颜色不会改变,就像它的应该。如果任何人有任何洞察为什么这种情况发生,我会非常感激它,如果你需要更多的细节,只是问。

If I remove the setNeedsDisplay, it doesn't crash, but the button color doesn't change like it's supposed to. If anybody has any insight into why this is happening, I would really appreciate it, and if you need more details, just ask.

编辑:我只是看了它再多一点。在我的-drawRect方法中,我调用[buttonColor set]。

I just looked into it a little more. In my -drawRect method, I call [buttonColor set]. By commenting that out, it no longer crashes, but again, it also doesn't change the button's color.

提前感谢,

thekmc

推荐答案

我假设你不使用ARC。

I assume that you're not using ARC.

当设置 buttonColor = bc 而不保留时,buttonColor将成为当前 autorelease pool flushes(假设它没有保留在其他地方)。

When setting buttonColor = bc without retaining, buttonColor will become a dangling pointer when the current autorelease pool flushes (assuming it's not retained elsewhere).

[self setNeedsDisplay]会调用drawRect:已被解除分配,这将导致您的应用程序崩溃。

[self setNeedsDisplay] will invoke drawRect: later and at that point, buttonColor may already have been deallocated which will crash your app when referring to it.

静态颜色不会崩溃的原因可能是由于UIKit保留这些

The reason that it doesn't crash for the static colors may be due to UIKit keeping ownership of these for later re-use.

通过将buttonColor设置为bc之后保留所有权,以使其仍然对drawRect:有效。

By retaining buttonColor after setting it to bc, you keep the ownership so that it's still valid for drawRect:.

这篇关于使用colorWithRed时,iOS应用程式崩溃:green:blue:alpha的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆