2014-10-06 3 views
3

나는 스 와이프 오른쪽 제스처를 수행하고자하는 뷰를 가지고 있습니다. 불행히도 EXC_BAD_ACCESS 오류가 나타납니다. 아무도 여기서 뭐가 잘못 됐는지 알아? 아래 코드를보십시오.클로저가있는 UIGestureRecognizer

extension UIView { 

    func addGestureRecognizerWithAction(nizer: UIGestureRecognizer, action:() ->()) { 

     class Invoker { 
      var action:() ->() 
      init(action:() ->()) { 
       self.action = action 
      } 
      func invokeTarget(nizer: UIGestureRecognizer) { 
       self.action() 
       println("Hi from invoker") 
      } 
     } 
     addGestureRecognizer(nizer) 
     nizer.addTarget(Invoker(action), action: "invokeTarget:") 
    } 
} 

class BugView: UIView { 

    override func awakeFromNib() { 
     super.awakeFromNib() 

     var swipeRight = UISwipeGestureRecognizer() 
     swipeRight.direction = UISwipeGestureRecognizerDirection.Right 
     self.addGestureRecognizerWithAction(swipeRight) { 
      println("Hi from the gesture closure") 
     } 
    } 
} 
+0

는 오류 출력을 보여줄 수 있습니까? –

+0

오류 출력은 다음과 같습니다. 스레드 1 : EXC_BAD_ACCESS (코드 = EXC_I386_GPFLT) – user1755189

+0

감사하지만 바로 아래의 디버거 출력을 의미합니다. –

답변

7

마지막으로 true가 맞았습니다. 위의 그의 대답에서 그는 Invoker을 NSObject의 하위 클래스로 만들 것을 제안함으로써 올바른 방향으로 나를 지적했습니다.

그러나 이것은 내 코드에서 유일한 실수는 아니 었습니다. 나는 스 와이프가 발생했을 때 이벤트를 처리하기 위해 만들어진 Invoker 개체가 이미 메모리에서 사라 졌다는 것을 알아 냈습니다. 나는 그것에 대한 언급이 그랬어야했듯이 폐쇄에 의해 점령되지 않았다고 생각한다. 지금은 내가 당신과 함께 공유하고 싶습니다이 기능을 구현하는 또 다른 방법으로 알아 낸 :

class UIGestureRecognizerWithClosure: NSObject { // must subclass NSObject otherwise error: "class does not implement methodSignatureForSelector: -- " !! 

    var closure:() ->() 

    init(view:UIView, nizer: UIGestureRecognizer, closure:() ->()) { 
     self.closure = closure 
     super.init() 
     view.addGestureRecognizer(nizer) 
     nizer.addTarget(self, action: "invokeTarget:") 
    } 

    func invokeTarget(nizer: UIGestureRecognizer) { 
     self.closure() 
    } 
} 

을 그리고이 조각은 당신이 코드를 사용하는 방법을 보여줍니다

var swipeRight = UISwipeGestureRecognizer() 
swipeRight.direction = UISwipeGestureRecognizerDirection.Right 

// swipeWrapper has to be defined as a property: var swipeWrapper:UIGestureRecognizerWithClosure? 
// -> this is needed in order to keep the object alive till the swipe event occurs 
swipeWrapper = UIGestureRecognizerWithClosure(view: self, nizer:swipeRight) { 
    println("Hi from the gesture closure") 
}