线程1:EXC_BAD_ACCESS(代码= 1,地址= 0x176b)

时间:2015-06-21 14:59:43

标签: ios swift exc-bad-access

当我尝试创建一个简单的应用程序时,我收到此错误:

@IBAction func pickButton(sender: UIButton) {
    numberLabel.text = String(format: "The number is %@", randomNumber) Thread 1: EXC_BAD_ACCESS (code=1, address=0x176b)
}

以下是完整代码:

import UIKit

class ViewController2: UIViewController {
    @IBOutlet weak var numberLabel: UILabel!
    @IBOutlet weak var pickButton: UIButton!
    var randomNumber = arc4random_uniform(10000) + 1
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func pickButton(sender: UIButton) {
        numberLabel.text = String(format: "The number is %@", randomNumber)
    }
}

请帮助,我不知道该怎么办。

2 个答案:

答案 0 :(得分:1)

randomNumber在整数中,而不是对象。格式说明符%@需要一个对象。使用适当的格式说明符,例如%u

有关文档,请参阅String Format Specifiers

答案 1 :(得分:1)

%@格式用于打印基础对象,例如NSStringNSNumber等。

var randomNumber = arc4random_uniform(10000) + 1

UInt32,打印时带有%u"无符号整数":

numberLabel.text = String(format: "The number is %u", randomNumber)

或者,使用%@并将整数转换为NSNumber

numberLabel.text = String(format: "The number is %@", NSNumber(unsignedInt: randomNumber))

但在您的情况下,最简单的解决方案是使用字符串插值

numberLabel.text = "The number is \(randomNumber)"