如何在swift中从另一个类调用方法

时间:2016-08-17 11:40:41

标签: ios swift

我有一个带有collectionView的viewcontroller类ViewController。我还有单件类FacebookManager用于从Facebook获取数据。

我想要做的是在facebook类中运行一个方法,然后在ViewController中调用一个方法来重新加载collectionView。

我尝试通过设置

在Facebook管理器中引用ViewController
class FacebookManager  {
   static let sharedInstance = FacebookManager()
   var vc:ViewController?
}

然后在ViewController中设置

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

然后在FacebookManager中调用

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

但这不起作用。

如何正确地做到这一点?

1 个答案:

答案 0 :(得分: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()
  }
}

但是你正在使用singleton类,因此将来多个类将使用这个类,如果你想通知多个类使用Notification方法,它很容易实现,应该在singleton类中使用

每当您想要通知时,都会在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()
   }
 }
相关问题