ios - 当我将 tintColor 放入其中时,Objective-C 数组中断

标签 ios objective-c arrays

今天遇到一个问题:NSArrayNSMutableArray。当我将应用程序 tintColor 作为其中的一个元素时,它们都会中断。

UIColor *temp = [[[UIApplication sharedApplication] delegate] window].tintColor;
self.usedSliderColors = [NSArray arrayWithObjects: temp,
                        [UIColor colorWithRed:255.0f/255.0f green:160.0f/255.0f blue:16.0f/255.0f alpha:1.0],
                        [UIColor colorWithRed:255.0f/255.0f green:50.0f/255.0f blue:50.0f/255.0f alpha:1.0], nil];

 NSLog([NSString stringWithFormat:@"%lu", (unsigned long)[self.usedSliderColors count]]);
 self.notificationLabel.backgroundColor = self.usedSliderColors[1];

在上面的场景中,我尝试使用 self.usedSliderColors[1] 或数组中的任何其他对象,应用程序中断,并显示数组为空的错误消息。但是,如果我在 use 语句之前放置一个 NSLog,它会给出 3 的大小。

另一方面,如果我将色调更改为另一种 UIColor,它会起作用:

self.usedSliderColors = [NSArray arrayWithObjects: [UIColor blueColor],
                        [UIColor colorWithRed:255.0f/255.0f green:160.0f/255.0f blue:16.0f/255.0f alpha:1.0],
                        [UIColor colorWithRed:255.0f/255.0f green:50.0f/255.0f blue:50.0f/255.0f alpha:1.0], nil];

 NSLog([NSString stringWithFormat:@"%lu", (unsigned long)[self.usedSliderColors count]]);
 self.notificationLabel.backgroundColor = self.usedSliderColors[1];

所以我的问题是是否有人知道解决这个问题的方法,或者我是否犯了一些愚蠢的错误?

最佳答案

您需要解决 tempnil 的情况,因为如果发生这种情况,则此行:

self.usedSliderColors = [NSArray arrayWithObjects: temp, [UIColor colorWithRed:255.0f/255.0f green:160.0f/255.0f blue:16.0f/255.0f alpha:1.0], [UIColor colorWithRed:255.0f/255.0f green:50.0f/255.0f blue:50.0f/255.0f alpha:1.0], nil];

与此相同:

self.usedSliderColors = [NSArray arrayWithObjects:nil];

这是一个包含 0 个项目的数组,因此索引 [1] 在边界之外。


如果你想确保所有 3 个项目都在你的数组中,你可以做类似的事情(当然,如果逻辑上适合你的工作流程):

self.usedSliderColors = [NSArray arrayWithObjects: temp?:[UIColor clearColor], [UIColor colorWithRed:255.0f/255.0f green:160.0f/255.0f blue:16.0f/255.0f alpha:1.0], [UIColor colorWithRed:255.0f/255.0f green:50.0f/255.0f blue:50.0f/255.0f alpha:1.0], nil];

因为在数组中包含 3 种颜色在句法上是完全完美的,现在索引 [1] 存在——您稍后要引用它。

关于ios - 当我将 tintColor 放入其中时,Objective-C 数组中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35704872/

相关文章:

IOS 日期选择器像弹出键盘功能?

objective-c - 合成的ivars存储在哪里?

c - 将一棵树展平成一个数组

ios - 全名的 Objective C 正则表达式

ios - 强制自动布局在 viewDidLoad 正确更新 UIView 框架

iphone - 以编程方式识别 iphone 设备

java - 为什么java中的数组值存储在堆中?

ruby - 如何根据另一个数组中的并行值对一个数组中的数据进行分组?

ios - 使用 2 个 NSTimers 时出现问题

objective-c - TableView 无/不更新