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.

lazyd3v
  • 426
  • 2
  • 13

2 Answers2

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)
    }
Kumar KL
  • 15,315
  • 9
  • 38
  • 60
  • 1
    Thank you, it works! Btw, I changed "var" to "let" and it works too! – lazyd3v Jun 13 '14 at 06:36
  • Hmm, actionSheet(myActionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int) doesn't work. Code is the same, but I add these lines to the class implementation. – lazyd3v Jun 13 '14 at 07:32
  • Check the delegates properly . ran into this code and then only i posted – Kumar KL Jun 13 '14 at 07:34
  • 1
    I missed "myActionSheet.delegate = self" line. Now everything works fine. Thank you – lazyd3v Jun 13 '14 at 07:55
  • 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. – Juan Carlos Ospina Gonzalez Jun 30 '14 at 13:45
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.

Deniz
  • 1,575
  • 1
  • 16
  • 27