Reputation: 21
When I try to make a simple app, I get this error:
@IBAction func pickButton(sender: UIButton) {
numberLabel.text = String(format: "The number is %@", randomNumber) Thread 1: EXC_BAD_ACCESS (code=1, address=0x176b)
}
Here is the full code:
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)
}
}
Please help, I don't know what I should do.
Upvotes: 1
Views: 2192
Reputation: 540065
The %@
format is for printing Foundation objects such as NSString
,
NSNumber
etc.
var randomNumber = arc4random_uniform(10000) + 1
is a UInt32
and that is printed with %u
for "unsigned integer":
numberLabel.text = String(format: "The number is %u", randomNumber)
Alternatively, use %@
and convert the integer to NSNumber
:
numberLabel.text = String(format: "The number is %@", NSNumber(unsignedInt: randomNumber))
But in your case the easiest solution is to use string interpolation:
numberLabel.text = "The number is \(randomNumber)"
Upvotes: 5
Reputation: 112873
randomNumber
in an integer, not an object. The format specifier %@
expects an object. Use an appropriate format specifier such as %u
.
See String Format Specifiers for documentation.
Upvotes: 2