简体   繁体   中英

How to call method from another class in swift

I have a viewcontroller class ViewController with collectionView. Also I have singleton class FacebookManager for fetching data from facebook.

What I want to do is to run a method in facebook class and then call a method in ViewController to reload collectionView.

I tried to make a reference to ViewController in Facebook manager by setting

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

Then setting in ViewController

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

And then calling in FacebookManager

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

But this doesn't work.

How to do this properly?

To provide communication between two or multiple classes there are two method that are recommended. 1) Delegation 2) Notification

In your given code to implement delegation method we have to create protocol and delegate property in FacebookManager. And assign view controller as a delegate to FacebookManger

Example:

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()
  }
}

But you are using singleton class therefore in future multiple class would be using this class and if you want to notify multiple classes use Notification method, which pretty easy to implement and should be use in singleton class

Post notification in FacebookManger whenever you want to notify:

 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()
   }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM