问题
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
Here's the setButtonColor: method:
-(void)setButtonColor:(UIColor *)bc{
buttonColor = bc;
[self 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.
EDIT: 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.
Thanks in advance,
thekmc
回答1:
I assume that you're not using ARC.
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] will invoke drawRect: later and at that point, buttonColor may already have been deallocated which will crash your app when referring to it.
The reason that it doesn't crash for the static colors may be due to UIKit keeping ownership of these for later re-use.
By retaining buttonColor after setting it to bc, you keep the ownership so that it's still valid for drawRect:.
来源:https://stackoverflow.com/questions/11318138/ios-app-crashes-when-using-colorwithredgreenbluealpha