gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 11:10:24 24 4
gpt4 key购买 nike

我有一个在背景中显示图像的 View 。该图像是从一组图像中挑选出来的,我正在使用随机函数来挑选它们。这样做时,应用程序会崩溃,但仅限于 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) 上设置 (isHomeScreenImage) 用户定义的检查属性:[setValue:forUndefinedKey:]:此类与键 isHomeScreenImage 的键值编码不兼容。

enter image description here

提前感谢您的帮助。 :)

最佳答案

arc4random()产生一个无符号的 32 位整数 ( UInt32 )。标准Int对应于 iPhone 5 上的 32 位(有符号)整数 ( iPhone 5 - 1.3 GHz dual core 32-bit ARMv7-A processor ), Int32类型,在这种情况下 Int(arc4random())上面这行平均有 50% 的时间会产生 (n)(整数溢出)运行时异常。为什么? UInt32 表示的数字的一半类型太大,无法用 Int32 表示类型。

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

您真的不需要使用 arc4random() 生成 32 位无符号整数范围内的任何随机数。功能;另一种方法是使用 arc4random_uniform()生成 0..<30 范围内的随机数.尝试用以下内容替换您标记为错误的行:

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

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

关于ios - 为什么这个随机函数代码会在 iPhone 5 和 5S 上崩溃。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35462750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com