使用colorWithRed时,iOS应用程式崩溃:green:blue:alpha

编程入门 行业动态 更新时间:2024-10-13 12:20:45
本文介绍了使用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

本文发布于:2023-11-27 23:24:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640019.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:程式   iOS   colorWithRed   alpha   blue

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!