【问题标题】:sending data back to the main ViewController xcode将数据发送回主 ViewController xcode
【发布时间】:2013-07-16 07:01:37
【问题描述】:

我正在尝试将数据从名为“waitViewController”的第二个视图控制器发送回主视图控制器。我使用的方法与我用来将数据从第一个发送到第二个的方法相同,只是反向发送。问题是 xcode 不允许我在 waitViewController.h 中使用 ViewController,而是希望我编写 UIViewController。我该如何解决? 我想要它是什么: 它给我的错误:

【问题讨论】:

    标签: xcode view uiviewcontroller


    【解决方案1】:

    可能是您需要使用“@class”而不是“#import ViewController.h”

    所以将导入语句替换为:

    @class ViewController;
    

    如果两个类的定义相互依赖,你需要这个,就像你的两个视图控制器类似乎做的那样。

    如果你最终使用@class,你必须在你的实现文件中导入'ViewController.h'。 @class 防止(否则)相互依赖的类定义的无限循环。据我了解,@class 的意思是“这个类“So​​meClass”存在,所以不用担心,即使我还不打算导入它的接口。”

    编辑:

    顺便说一句,我觉得我应该提一下 @class 是一种 hack,还有另一种更优雅的解决方案:(正式或非正式)协议。要使用正式协议:将协议定义放在“WaitViewController.h”的顶部:

    @protocol WaitControllerDelegate
     -(void) useThisNewData: (NSWhateverDataType *) theData; 
    - (void) useThisOtherData:(SomeOtherDataType) otherData;
    @end
    

    在WaitViewController 接口中,不要将'turnData' 定义为'ViewController *' 类型。而是将其定义为类型“id”:

    @property (nonatomic, assign) id <WaitControllerDelegate> turnDataDelegate;
    

    (请注意,假设 ViewController 拥有对 WaitViewController 的“保留”引用,并且您不希望两个对象之间存在强引用,则使用“分配”而不是“保留”——它们将创建一个“保留循环”,即相互永远不会允许彼此解除分配。) 在WaitViewController实现文件中,每当需要发回数据时,调用

    [turnDataDelegate useThisNewData: someData];
    

    在 ViewController.h 中,宣布您正在采用“WaitControllerDelegate”协议:

    @interface ViewController : UIViewController <WaitControllerDelegate> {
    

    然后,在 ViewController.m 中实现“WaitControllerDelegate”方法,就像您执行任何其他方法一样,但您不必在接口中声明它们:

    - (void) useThisNewData: (NSWhateverDataType *) theData {
       ...do whatever you want
    }
    

    这种方法需要做更多的工作,但效果更好,因为它允许“WaitViewController”类更加独立,并且通常在理论上使您的类更具可重用性。

    【讨论】:

    • 成功了!你是救世主!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多