2016-08-17 3 views
1

viewcontroller 클래스 ViewController과 collectionView가 있습니다. 또한 페이 스북 (Facebook)에서 데이터를 가져 오는 싱글 톤 클래스 FacebookManager 있습니다.신속하게 다른 클래스의 메서드를 호출하는 방법

내가하고 싶은 일은 facebook 클래스에서 메소드를 실행 한 다음 ViewController에서 메소드를 호출하여 collectionView를 다시로드하는 것입니다.

나는 그런 FacebookManager

func myMethod() { 
    vc.collectionView.reloadData() 
} 

그러나 아무튼에서 호출하는 다음의 ViewController

class ViewController: { 
    func viewDidLoad() { 
     FacebookManager.sharedInstance.vc = self 
    } 
} 

에 설정하고

class FacebookManager { 
    static let sharedInstance = FacebookManager() 
    var vc:ViewController? 
} 

를 설정하여 페이스 북 관리자에서의 ViewController에 대한 참조를 만들려고 일하지 마라.

올바르게 수행하는 방법은 무엇입니까?

+0

'FacebookManager'는 싱글 톤이며 모든 곳에서 액세스 할 수 있으므로 콜렉션 뷰가 포함 된 컨트롤러에서 데이터를 가져 오는 메소드를 호출하십시오. – vadian

+0

예, 그렇다면 어떻게 FacebookManager에서 ViewController를 다시 호출 할 수 있습니까? –

+0

대리자 메서드 또는 완료 블록을 사용합니다. – vadian

답변

0

두 개 또는 여러 클래스 간의 통신을 제공하려면 두 가지 방법이 권장됩니다. 1) 위임 2) 우리가 프로토콜을 만들고 FacebookManager 재산을 위임 할 수있는 위임 방법을 구현하여 주어진 코드에서 알림

. 그리고

예 FacebookManger

에 대리인으로 뷰 컨트롤러를 할당 :

protocol FacebookManagerDelegate: class { 
    func refreshData() 
} 

class FacebookManager { 
    var weak delegate:FacebookManagerDelegate? 
    func myMethod() { 
    delegate?.refreshData() 
    } 
} 

class ViewController: FacebookManagerDelegate { 
    ViewDidLoad() { 
    FacebookManager.sharedInstance.delegate = self 
    } 

func refreshData() { 
    self.collectionView.reloadData() 
    } 
} 

하지만이 클래스를 사용하는 것 때문에 향후 여러 클래스에서 싱글 톤 클래스를 사용하고 여러 클래스 통지 방법을 사용 통지하려는 경우, 이는 아주 쉽게 구현하고

당신이 통지 FacebookManger에 게시물 통지를 할 때마다 싱글 톤 클래스에 사용되어야한다 :

class FacebookManager { 
    func myMethod() { 
    NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil) 
    } 
} 

class ViewController { 
    ViewDidLoad() { 
    NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(reloadData(_:)), name: NotificationName, object: nil) 
    } 
    deinit { 
    NSNotificationCenter.defaultCenter().removeObserver(self) 
    } 

func reloadData(notification: NSNotification) { 
    self.collectionView.reloadData() 
    } 
} 
+1

가장 편리한 방법은 언급하지 않았습니다. 3) 콜백/완료 블록 – vadian

+0

물론입니다. 감사 –

관련 문제