EXC_BAD_ACCESS when trying to init UIActionSheet in Swift
Asked Answered
G

2

9

My program compiles successfully, but when I press the button, it crashes. Here's the viewController.swift:

import UIKit

class ViewController: UIViewController, UIActionSheetDelegate{

@IBOutlet var button:UIButton

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 buttonPressed(AnyObject) {
    let choice = UIActionSheet(title: "Select source", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles:"camera", "libary")
    choice.showInView(self.view)
}
}

The error appears on this line:

let choice = UIActionSheet(title: "Select source", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles:"camera", "library")

And here's error text:

EXC_BAD_ACCESS (code=2, address=0x0)

I tried to switch let to var, ran it on different simulators, but the result is same.

Guthrey answered 13/6, 2014 at 5:22 Comment(0)
C
6

Tried, but unable to figure out the exception. Finally I got a solution like this :

  var myActionSheet:UIActionSheet = UIActionSheet()

        var title : String? = "Select Source"
        myActionSheet.title  = title
            myActionSheet.delegate = self
        myActionSheet.addButtonWithTitle("camera")
        myActionSheet.addButtonWithTitle("Library")
        myActionSheet.addButtonWithTitle("Cancel")

        myActionSheet.cancelButtonIndex = 2 
        myActionSheet.showInView(self.view)

UIActionSheet Delegate

func actionSheet(myActionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int){
        println("the index is %d", buttonIndex)
    }
Coleoptile answered 13/6, 2014 at 6:26 Comment(5)
Thank you, it works! Btw, I changed "var" to "let" and it works too!Guthrey
Hmm, actionSheet(myActionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int) doesn't work. Code is the same, but I add these lines to the class implementation.Guthrey
Check the delegates properly . ran into this code and then only i postedColeoptile
I missed "myActionSheet.delegate = self" line. Now everything works fine. Thank youGuthrey
I was having the same issue and random crashes when i would NSLog() the view of the controller running the code. It looks like the constructor with parameters has some kind of serious bug in it.Buskin
S
0

You have to end otherButtonTitles parameters with nil. For example, in your case it should be:

otherButtonTitles:"camera", "libary", nil

It is not Swift specific, it is the same in objective-c too.

Selmore answered 13/12, 2014 at 13:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.