为什么这个随机函数代码在iPhone 5和5S上崩溃。

我认为在后台显示图像。 图像是从图像数组中挑选的,我使用随机函数来选取它们。 在这样做的应用程序崩溃,但只在iPhone 5 / 5S。

这是我的代码:…

//Images let rest28 = UIImage(named: "rest28") let rest29 = UIImage(named: "rest29") let rest30 = UIImage(named: "rest30") // image Array imageArray = [rest1!, rest3!, rest4!, rest5!, rest6!, rest7!, rest8!, rest9!, rest10!, rest11!, rest12!, rest13!, rest15!, rest17!, rest18!, rest21!, rest22!, rest24!, rest25!, rest26!, rest27!, rest28!, rest29!, rest30!] // Picking a number in the array of images. let randomImageSelection = 0 + Int(arc4random()) % (0 - imageArray.count - 1) backgroundImage.image = imageArray[randomImageSelection] 

这是我在randomImageSelection函数上得到的崩溃:

– 在(UIView):[setValue:forUndefinedKey:]上设置(isHomeScreenImage)用户定义的检查属性失败:该类不是键值isHomeScreenImage的键值编码。

在这里输入图像说明

我在这里先向您的帮助表示感谢。 🙂

arc4random()产生一个无符号的32位整数( UInt32 )。 标准Int对应于iPhone 5( iPhone 5 – 1.3 GHz双核32位ARMv7-A处理器 ) Int32types上的32位(带符号)整数,在这种情况下Int(arc4random())将产生(n) (整数溢出)运行时exception〜上述运行时间的平均值的50%。 为什么? 由UInt32types表示的一半数字太大,无法用Int32types表示。

 print(INT32_MAX) // 2147483647 print(UINT32_MAX) // 4294967295 <-- max return of arc4random() 

您真的不需要使用arc4random()函数在32位无符号整数的范围内生成任何随机数; 另一种方法是使用arc4random_uniform()生成一个范围为arc4random_uniform()的随机数。 尝试用以下代码replace已标记为错误的行:

 let randomImageSelection = arc4random_uniform(UInt32(imageArray.count)) /* random Integer in: 0 ..< imageArray.count */ 

密切相关的线程(这可能是重复的),谢谢@Eric D.

  • 应用程序崩溃iPhone 5及以下