【问题标题】:Passing a delegate to another view controller's delegate将委托传递给另一个视图控制器的委托
【发布时间】:2018-01-01 04:58:29
【问题描述】:

我正在努力在一个用 Objective-C 编写的应用程序中构建一个功能。我不能发布代码,但我会尽量描述我的世界。我面临的问题与代表有关。

  1. AlphaViewControllerConnectionView 作为其delegate 之一。它有助于添加对提供给AlphaViewController 的数据执行一些操作,我们在AlphaViewController's 视图上显示输出。

  2. 当您单击AlphaViewController 中的按钮时,我会显示UIAlertController。我可以从中单击一个按钮打开ReportViewBetaViewController 创建 ReportView

  3. BetaViewController 具有 ReportGenerator 作为其 delegateReportGenerator 有助于生成一些我在 BetaViewController's 视图中呈现的 HTML。

我的问题是,我想在ReportGenerator 中使用ConnectionView's 输出(我相信它是AlphaViewControllerConnectionView 对象的一部分) 来处理它然后渲染数据在BetaViewController's 视图中的 HTML 中。

我一直在四处寻找解决方案,但无法弄清楚任何事情。我不擅长代表。

请帮助我在这里实现我的目标。很抱歉,我无法发布代码。

【问题讨论】:

  • 你能指定这是什么类型的输出吗?字符串、图片等??
  • @luckyShubhra 输出属于 ConnectionView 类型。

标签: ios objective-c uiviewcontroller delegates


【解决方案1】:
  1. 您可以在推送之前将ConnectionView's 的输出从AlphaViewController 传递给BetaViewController。当您将BetaViewController 指定为ReportGenerator 的代表时,将数据(即ConnectionView's)输出到ReportGenerator 并让ReportGenerator 对其进行处理,然后在BetaViewController's 视图中以HTML 格式呈现数据。

说起来可能很复杂,但可以做到。

  1. 还有第二种方法比上面使用AppDelegate 简单得多。您可以在 AppDelegate 类中声明和定义一个属性,并从类中的任何位置访问它。

    //Interface:
    
    @interface MyAppDelegate : NSObject  {
       NSString *yourString; // Declare your object
    }
    
    @property (nonatomic, strong) NSString *yourString;
    ...
    @end
    
    //and in the .m file for the App Delegate     
    @implementation MyAppDelegate
    
    @synthesize yourString;
    yourString = some string;
    
    @end
    
    //You can access the property to save and retrieve your file. You can save 
    MyAppDelegate *appDelegate = (MyAppDelegate*)[[UIApplication sharedApplication] delegate];
    appDelegate.yourString = some NSString;     //..to write
    

您可以根据您的要求读取 BetaViewController 或 ReportGenerator 中的值

MyAppDelegate *appDelegate = (MyAppDelegate*)[[UIApplication sharedApplication] delegate];
someString = appDelegate.myString;  //..to read

为了不。您可以创建模型类并按照上面定义的方式访问它的属性。

【讨论】:

  • AppDelagate 方法更好,因为您可以在项目中的任何位置访问它。
  • @luckyShubhra 非常感谢您提供此解决方案。它完美无缺!但是,这里有一个问题。当我从 BetaViewController 回到 AlphaViewController 时,ConnectionView 的输出从屏幕上消失了。似乎对象已完全传递给 BetaViewController 但无论如何都不会被 AlphaViewController 保留。您对为什么会发生这种情况有任何意见吗?我自己修复它,但无论如何想知道它的原因。
  • 对不起我的错误。我从不使用 ARC 的旧项目中复制了它。将 AppDelegate 中的属性更改为强且非原子的。
猜你喜欢
  • 1970-01-01
  • 2013-08-27
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
  • 2018-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多