UnlimitedAlpha UnlimitedAlpha - 1 year ago 55
iOS Question

UIIButton IBAction will not work while using random numbers and setting images

I have a program i am working on that is supposed to output a random amount of dice each with a random side showing when the device is shaken. I have gotten that part to work, but now I want to add in a button that when pressed selects one of the dice being sides being displayed as the only side being displayed. I have the button added through my storyboard and this function sets some attributes:

func setButton(show: Bool = true) {
if show == true{
observerButton.setTitle("Observe", forState: UIControlState.Normal)
observerButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
observerButton.setTitleShadowColor(UIColor.grayColor(), forState: UIControlState.Normal)
observerButton.setTitle("", forState: UIControlState.Normal)
observerButton.setTitleColor(UIColor.clearColor(), forState: UIControlState.Normal)
observerButton.setTitleShadowColor(UIColor.clearColor(), forState: UIControlState.Normal)

This function is used to enable the button after the device is shaken. Here is the code in the IBAction:

@IBAction func observe(sender: UIButton) {
if shaked == true{
var chosenDice: Int = Int(arc4random()) % amountOfNumbers
dice[0].image = diceImages[diceDisplayed[chosenDice]-1]
shaked = false

diceImages is an array that contains an image of each side of a die. amountOfNumbers is generated in another function and is a random number from 1-6 and is used to tell how many dice will be displayed. resetDice() sets all of the dice to "nil" and shaked is set to true after the device is shaken (kind of obvious but I just wanted to cover everything). Dice is my IBOutlet array for the UIImageViews where the dice are displayed.

When I run this program, everything runs fine, but as soon as I push the button, the app stops (doesn't crash entirely, but Xcode comes into my view and the button code is not visibly executed) with the error,

"EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode = 0x0)"

next to the close bracket of the if statement in the observe IBAction function, and it says in the console, "(lldb)" There are no syntax errors.

I know arc4random_uniform() will not work instead of the arc4random() % amountOfNumbers because that function requires a UInt32 where amountOfNumbers is an Int.

Answer Source

arc4random() can generate values that are too high to fit inside a normal Int, which is why their default type isUInt32, so they can store values that large. Exceeding the limit of the Int resulted in the error. I fixed this by changing the arc4random() to a rand() which created smaller values that could fit inside an Int.