UISwitch setThumbTintColor导致崩溃(仅iOS 6)?

更新:从苹果收到一封邮件说,该错误/问题已被修复,下一个SDK版本将不会有这个问题。 和平!

我在我的AppDelegate的代码中有这个:

- (void) customizeAppearance { [[UISwitch appearance] setOnTintColor:[UIColor colorWithRed:0 green:175.0/255.0 blue:176.0/255.0 alpha:1.0]]; [[UISwitch appearance] setTintColor:[UIColor colorWithRed:255.0f/255.0f green:255.0f/255.0f blue:255.0f/255.0f alpha:1.000f]]; [[UISwitch appearance] setThumbTintColor:[UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0]]; } 

然后我调用- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

我也用ARC。 在iOS 6中,我的应用程序不断崩溃。 我启用NSZombie,它一直说: *** -[UIDeviceRGBColor release]: message sent to deallocated instance 0x9658eb0

现在我已经意识到上述的一个完美可重复的stream程。 当我在customAppearance中单独注释掉setThumbTintColor行时,一切正常。 当我使用setThumbTintColor行代替时,应用程序每次都以完全相同的方式崩溃。

这是UISwitch / setThumbTintColor / UIColor的任何人都知道的问题? 如果不是开关颜色,还有什么原因呢?

我也在做这个教程,并有同样的问题。 (不知道为什么你不经历这个,因为我的手input的代码和解决scheme代码对我来说都有同样的问题?)

第一轮比赛可能会发生,但回去后下一轮比赛将失败。

设置全局exception断点之后,当生成exception时,我可以在调用堆栈中看到thumbColorTint。 我猜测这个对象被释放得太早了。 要解决我在我的应用程序委托中创build了一个属性..(你不需要在应用程序委托中只是设置UISwitch外观的对象,在我的情况下是appdelegate)

 @interface SurfsUpAppDelegate() @property (strong, nonatomic) UIColor *thumbTintColor; @end 

然后我就这样设置

 [self setThumbTintColor:[UIColor colorWithRed:0.211 green:0.550 blue:1.000 alpha:1.000]]; [[UISwitch appearance] setThumbTintColor:[self thumbTintColor]]; 

现在一切都按预期工作,因为对象没有提早发布。 这可能是一个缺陷,即使仍然需要,对象也会被释放。 UISwitch似乎有一个API的缺陷:(

我也遇到了苹果的UISwitch过度释放这个bug。 我有一个类似的解决scheme,但我认为它只是一点点更好,因为它不需要添加一个无关的属性:

 UIColor *thumbTintColor = [[UIColor alloc] initWithRed:red green:green blue:blue alpha:alpha]]; //we're calling retain even though we're in ARC, // but the compiler doesn't know that [thumbTintColor performSelector:NSSelectorFromString(@"retain")]; //generates warning, but OK [[UISwitch appearance] setThumbTintColor:[self thumbTintColor]]; 

不利的一面是,它确实会创build一个编译器警告,但是 – 这里确实存在一个bug,而不是我们的!

现在,我要按照比尔的回答来解决这个问题:

 // SomeClass.m @interface SomeClass () // ... @property (weak, nonatomic) IBOutlet UISwitch *thumbControl; @property (strong, nonatomic) UIColor *thumbControlThumbTintColor; // ... @end @implementation SomeClass // ... - (void)viewDidLoad { // ... self.thumbControl.thumbTintColor = self.thumbControlThumbTintColor = [UIColor colorWithRed:0.2 green:0.0 blue:0.0 alpha:1.0]; // ... } // ... @end