ios – 文件范围? Swift代表和协议

前端之家收集整理的这篇文章主要介绍了ios – 文件范围? Swift代表和协议前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在努力构建一个新的 Swift应用程序,大致基于一个旧的Obj-c应用程序.我目前正在为代表们工作

这是我的obj-c代码在.h文件中的样子

  1. @interface MyAppViewController : CustomViewController
  2. @property (nonatomic,weak) id<MyAppViewControllerDelegate> delegate;
  3. @end
  4.  
  5. @protocol MyAppViewControllerDelegate <NSObject>
  6. - (void)myAppViewController:(MyAppViewController *)controller loggedInStudent: (MYStudent *)student;
  7. - (void)myAppViewControllerWantsSignUp:(MyAppViewController *)controller;
  8. @end

在SWIFT我做了:

  1. class MyAppViewController: CustomViewController {
  2.  
  3. var delegate: MyAppViewControllerDelegate?
  4. protocol MyAppViewControllerDelegate{
  5. func myAppViewController(controller: MyAppViewController,loggedInStudent: MYStudent)
  6. func myAppViewControllerWantsSignUp(controller: MyAppViewController)

我已经做了很多阅读和研究,所以我认为我做的基本上是正确的(尽管很快,但是……)

我收到此错误,“声明仅在文件范围内有效”,协议MyAppViewControllerDelegate {
我认为这与在类中声明它有关,所以我把它移出来,只是现在我的代码中的代码不能识别我声明的委托变量.

有任何想法吗?

解决方法

应该是这样的:
  1. protocol MyAppViewControllerDelegate {
  2. func myAppViewController(controller: MyAppViewController,loggedInStudent: MYStudent)
  3. func myAppViewControllerWantsSignUp(controller: MyAppViewController)
  4. }
  5.  
  6. class MyAppViewController: CustomViewController {
  7.  
  8. var delegate: MyAppViewControllerDelegate?
  9. }

虽然,如果您遵循一个常见模式,其中拥有MyAppViewController的对象也是其委托,这可能会导致内存问题.你可以使用类输入来允许弱委托,如下所示:

  1. protocol MyAppViewControllerDelegate : class {
  2. func myAppViewController(controller: MyAppViewController,loggedInStudent: MYStudent)
  3. func myAppViewControllerWantsSignUp(controller: MyAppViewController)
  4. }
  5.  
  6. class MyAppViewController: CustomViewController {
  7.  
  8. weak var delegate: MyAppViewControllerDelegate?
  9. }

这有点限制,因为它要求您为您的委托使用一个类,但它将有助于避免保留周期:)

猜你在找的iOS相关文章