我正在努力构建一个新的
Swift应用程序,大致基于一个旧的Obj-c应用程序.我目前正在为代表们工作
@interface MyAppViewController : CustomViewController @property (nonatomic,weak) id<MyAppViewControllerDelegate> delegate; @end @protocol MyAppViewControllerDelegate <NSObject> - (void)myAppViewController:(MyAppViewController *)controller loggedInStudent: (MYStudent *)student; - (void)myAppViewControllerWantsSignUp:(MyAppViewController *)controller; @end
在SWIFT我做了:
class MyAppViewController: CustomViewController { var delegate: MyAppViewControllerDelegate? protocol MyAppViewControllerDelegate{ func myAppViewController(controller: MyAppViewController,loggedInStudent: MYStudent) func myAppViewControllerWantsSignUp(controller: MyAppViewController)
我已经做了很多阅读和研究,所以我认为我做的基本上是正确的(尽管很快,但是……)
我收到此错误,“声明仅在文件范围内有效”,协议MyAppViewControllerDelegate {
我认为这与在类中声明它有关,所以我把它移出来,只是现在我的代码中的代码不能识别我声明的委托变量.
有任何想法吗?
解决方法
应该是这样的:
protocol MyAppViewControllerDelegate { func myAppViewController(controller: MyAppViewController,loggedInStudent: MYStudent) func myAppViewControllerWantsSignUp(controller: MyAppViewController) } class MyAppViewController: CustomViewController { var delegate: MyAppViewControllerDelegate? }
虽然,如果您遵循一个常见模式,其中拥有MyAppViewController的对象也是其委托,这可能会导致内存问题.你可以使用类输入来允许弱委托,如下所示:
protocol MyAppViewControllerDelegate : class { func myAppViewController(controller: MyAppViewController,loggedInStudent: MYStudent) func myAppViewControllerWantsSignUp(controller: MyAppViewController) } class MyAppViewController: CustomViewController { weak var delegate: MyAppViewControllerDelegate? }
这有点限制,因为它要求您为您的委托使用一个类,但它将有助于避免保留周期:)