[英]How to call method from another class in swift
I have a viewcontroller class ViewController
with collectionView. 我有一个带有collectionView的viewcontroller类
ViewController
。 Also I have singleton class FacebookManager
for fetching data from facebook. 我还有单例类
FacebookManager
从FacebookManager
获取数据。
What I want to do is to run a method in facebook class and then call a method in ViewController to reload collectionView. 我想要做的是在facebook类中运行一个方法,然后在ViewController中调用一个方法来重新加载collectionView。
I tried to make a reference to ViewController in Facebook manager by setting 我尝试通过设置在Facebook管理器中引用ViewController
class FacebookManager {
static let sharedInstance = FacebookManager()
var vc:ViewController?
}
Then setting in ViewController 然后在ViewController中设置
class ViewController: {
func viewDidLoad() {
FacebookManager.sharedInstance.vc = self
}
}
And then calling in FacebookManager 然后在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
1)授权2)通知
In your given code to implement delegation method we have to create protocol and delegate property in FacebookManager. 在您给定的实现委托方法的代码中,我们必须在FacebookManager中创建协议和委托属性。 And assign view controller as a delegate to FacebookManger
并将视图控制器指定为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 但是你正在使用singleton类,因此将来多个类将使用这个类,如果你想通知多个类使用Notification方法,这很容易实现,应该在singleton类中使用
Post notification in FacebookManger whenever you want to notify: 每当您想要通知时,都会在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()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.