Swift - NSNotificationCenter 알림 전송 및 알림 수신

2723 단어

알림(NSNotification) 소개


여기서 말한 통지는 사용자에게 보내는 통지 소식이 아니라 시스템 내부에서 정보를 전달하는 통지를 가리킨다.통지를 소개하기 전에 관찰자 모델이 무엇인지 알아야 한다.
관찰자 모드(Observer): 한 대상이 상태가 변할 때 다른 대상에게 통지하는 것을 말한다.참가자들은 다른 대상이 구체적으로 무엇을 하는지 알 필요가 없다.이것은 결합도를 낮추는 디자인이다.흔히 볼 수 있는 사용 방법은 관찰자가 감청을 등록하고 상태가 바뀔 때 모든 관찰자가 통지를 받는 것이다.
MVC에서 관찰자 모드는 모델 대상과 View 대상이 교류할 수 있도록 허락해야 하며 직접적인 연관이 있을 수 없다는 것을 의미한다.코코아는 두 가지 방식으로 관찰자 모델을 실현했다. 하나는 Key-Value Observing(KVO)이고 다른 하나는 본고에서 말하고자 하는 Notification이다.

관찰자 추가

NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(TranscriptDetailViewController.getExamId(_:)), name: "examDidChanged", object: nil)
        
NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(TranscriptDetailViewController.getExamCourseId(_:)), name: "examCourseDidChanged", object: nil)
    func getExamId(notification:NSNotification) {
        let userInfo = notification.userInfo as! [String: AnyObject]
        let examId = userInfo["examId"] as! String
        let examName = userInfo["examName"] as! String

        print("\(name)  , [\(examId),\(examName)]")
        NSUserDefaultsHelper().setDefault("examId", value: examId)
        NSUserDefaultsHelper().setDefault("examName", value: examName)
        
        getStudentReport()
        
    }

    func getExamCourseId(notification:NSNotification) {
        let userInfo = notification.userInfo as! [String: AnyObject]
        let examCourseId = userInfo["examCourseId"] as! String
        let courseName = userInfo["courseName"] as! String
        
        print("\(name)  , [\(examCourseId),\(courseName)]")
        NSUserDefaultsHelper().setDefault("examCourseId", value: examCourseId)
        
        getStudentReport()        
    }

알림 스니퍼 제거


필요하지 않으면 메모리 낭비나 붕괴를 피하기 위해 상응하는 알림을 취소에 등록하는 것을 잊지 마십시오
    deinit {
        //  
        //  , , 
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

알림 보내기

NSNotificationCenter.defaultCenter().postNotificationName("examDidChanged",
                                                                      object: self, userInfo: ["examId":examInfo.examId,"examName":examInfo.examName])
NSNotificationCenter.defaultCenter().postNotificationName("examCourseDidChanged",
                                                                      object: self, userInfo: ["examCourseId":examCoureseInfo.examCourseId,"courseName":examCoureseInfo.courseName])

좋은 웹페이지 즐겨찾기