2

I have the Test class with button_action optional closure:

class Test : CustomViewFromXib {
    var button_action : (() -> ())?
    @IBAction func button_pressed(sender: AnyObject) {
        if let action = button_action {
            action()
        }
    }
}

This is how I use this class:

 let test_view = Test(frame: CGRect.nullRect)
 self.view.addSubview(test_view)
 test_view.button_action = {
    () -> () in
    print("test")
 }

I get EXC_BAD_ACCESS error at line:

test_view.button_action = {
    () -> () in
    print("test")
}

I don't know why, because I just want to set initial value. Is it possible to do it that way?

UPDATE:

I understood, that no one property or method can't be called from my object. Not only closures, but Strings (for example) too.

UPDATE 2:

This is my little example of code that reproduces the problem. I think I have a problem with initializers... https://www.dropbox.com/s/1d8fvxm0es9b5n4/TestInit.zip

(XCode 6 Beta 5)

Community
  • 1
  • 1
John Kakon
  • 2,531
  • 4
  • 24
  • 28
  • I created a test project, with similar code and it works for me - but I added the Test View in interface builder (to connect a button). So I would say it's nothing to do with setting the button_action variable, or the types of the closure – James Alvarez Aug 13 '14 at 12:22
  • Hmm.. I tried to create property `test : String = "xxx"` and access it by test_view.test = "zzz" and it doesn't work too. Also I added method test() and I can't call it. – John Kakon Aug 13 '14 at 13:10

1 Answers1

0

Write code

let test_view = Test(frame: CGRect.nullRect)
 self.view.addSubview(test_view)
 test_view.button_action = {
    () -> () in
    print("test")
 }

instead of

let test_view = Test(frame: CGRect.nullRect)
 self.view.addSubview(test_view)
 test_view.button_action = { [unowned self]
    () -> () in
    print("test")
 }

Here is exact detail theoretical answer Shall we always use [unowned self] inside closure in Swift https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html

Community
  • 1
  • 1
Tirth
  • 7,801
  • 9
  • 55
  • 88