2016-06-12 1 views
0

작은 Swift 애플리케이션으로 놀고 있습니다. 사용자는 응용 프로그램의 메뉴에서 "새로 만들기"를 클릭하여 많은 수의 MainWindow 인스턴스를 원하는대로 만들 수 있습니다.스위프트 : addObserverForName의 usingBlock에서 가능한 removeObserver 순환 참조

응용 프로그램 대리인은 MainWindowController에 입력 된 배열을 보유합니다. 컨트롤러는 MainWindowController 배열에서 컨트롤러를 제거하기 위해 NSWindowWillCloseNotification으로 감시됩니다. 관찰자의 제거가 제대로 된 경우

문제는 지금 - 나는 관찰자에 순환 참조가있을 수 있습니다 두려워,하지만 난 그 테스트하는 방법을 모른다 :

class ApplicationDelegate: NSObject, NSApplicationDelegate { 

    private let notificationCenter = NSNotificationCenter.defaultCenter() 
    private var mainWindowControllers = [MainWindowController]() 

    func newWindow() { 
    let mainWindowController = MainWindowController() 
    let window = mainWindowController.window 
    var observer: AnyObject? 
    observer = notificationCenter.addObserverForName(NSWindowWillCloseNotification, 
                object: window, 
                queue: nil) { (_) in 
      // remove the controller from self.mainWindowControllers 
      self.mainWindowControllers = self.mainWindowControllers.filter() { 
       $0 !== mainWindowController 
      } 
      // remove the observer for this mainWindowController.window 
      self.notificationCenter.removeObserver(observer!) 
    } 
    mainWindowControllers.append(mainWindowController) 
    } 

} 

답변

0

일반적으로 NSNotificationCenter으로 등록 된 블록에는 self이 소유되지 않은 것으로 지정해야합니다. 이렇게하면 블록에 self에 대한 강력한 참조가 유지됩니다. 클로저의 매개 변수 목록 앞에있는 캡처 목록을 사용하면됩니다.

{ [unowned self] (_) in 
    // Block content 
} 
+0

고맙습니다. 내 질문은 실제로 순환 참조가 있는지 테스트하는 방법 이었지만, 충분히 구체적이지는 않다고 말해야합니다 - 나쁘다. _notificationCenter.debugDescription_에서 _NSWindowWillCloseNotification_이있는 행을 필터링하여 테스트하는 방법을 찾았습니다. – Eliott