【问题标题】:iOS Swift Type Conversation Math causing app to CrashiOS Swift 类型对话数学导致应用程序崩溃
【发布时间】:2014-08-05 07:30:16
【问题描述】:

我的代码旨在将一个小的 UIView 作为子视图放置在随机 X 坐标处。

如果我将视图放置在固定位置,它可以工作,但是当我计算随机位置时,我的应用程序会崩溃。代码如下:

    @IBOutlet var gameView : UIView
    let DROP_SIZE = CGSize(width: 40, height: 40)

    @IBAction func tap(sender : AnyObject) {
        self.drop()
    }

    func drop() {
        var frame = CGRect()
        frame.origin = CGPointZero
        frame.size = DROP_SIZE
        var x = Int(arc4random()) % Int(self.gameView.bounds.size.width) / Int(DROP_SIZE.width)
        frame.origin.x = CGFloat(x) * CGFloat(DROP_SIZE.width)
        var dropView: UIView = UIView(frame: frame)
        dropView.backgroundColor = randomColor()
        self.gameView.addSubview(dropView)

    }

每当调用 self.drop() 时,我的应用就会崩溃

如果我注释掉 var x & frame.origin.x 我的应用程序不会崩溃

所以我知道问题出在这两行代码上:

var x = Int(arc4random()) % Int(self.gameView.bounds.size.width) / Int(DROP_SIZE.width)
frame.origin.x = CGFloat(x) * CGFloat(DROP_SIZE.width)

这些变量的转换方式导致应用程序崩溃,因为如果我使用固定的 x 原点,例如 frame.origin.x = 100,那么应用程序将按预期工作。

更新:

因为 arc4random 返回 UInt32 它会在尝试将其转换为 Int 时溢出

我用这个代替

var x = UInt32(arc4random()) % UInt32(self.gameView.bounds.size.width) / UInt32(DROP_SIZE.width)
frame.origin.x = CGFloat(x) * CGFloat(DROP_SIZE.width)

【问题讨论】:

  • 崩溃时有错误提示吗?
  • 我收到的错误突出显示 self.drop() 的文本:线程 1:EXC_BAD_INSTRUCTION(code=EXC+l386_INVOP, subcode=0x0)
  • 有趣的是有时它会立即崩溃,有时它在最初的几次点击中起作用然后崩溃
  • arc4random 返回一个 UInt32。有一半时间它会溢出 Int32 并在强制边界检查时崩溃。查看链接的副本。

标签: ios iphone casting type-conversion swift


【解决方案1】:

因为 arc4random 返回 UInt32 它会在尝试将其转换为 Int 时溢出

我用这个代替

var x = UInt32(arc4random()) % UInt32(self.gameView.bounds.size.width) / UInt32(DROP_SIZE.width)
frame.origin.x = CGFloat(x) * CGFloat(DROP_SIZE.width)

这个问题类似:Crash when casting the result of arc4random() to Int

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 2020-03-17
    相关资源
    最近更新 更多