如何正确地从一个UIViewController传递NSArray/NSMutableArray到另一个 [英] How to properly pass NSArray / NSMutableArray from one UIViewController to another

查看:43
本文介绍了如何正确地从一个UIViewController传递NSArray/NSMutableArray到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用的iPhone应用程序会定期终止...我感到这是由于我如何在多个视图控制器之间访问共享的NSArray.所以...

An iphone app I'm working on is terminating periodically ... and I have a feeling it is because of how I'm accessing a shared NSArray amongst several view controllers. So ...

在多个ViewController之间传递NSArray/NSMutableArray的最佳方法是什么?所有这些控制器都可以将其修改和/或设置为nil或其他任何值?

What is the best way to pass NSArray/NSMutableArray amongst several ViewControllers ... all of which can modify and/or set it to nil or whatever?

谢谢

推荐答案

通常有两种方法.

在第一种方法中,当实例化下一个视图控制器时,可以将数组属性设置为从当前(即将成为上一个或父级)视图控制器中继承":

In the first approach, when you instantiate your next view controller, you could set an array property to "inherit" from the current (soon-to-be previous or parent) view controller:

MyNextViewController *_myNextViewController = [[MyNextViewController alloc] initWithNibName:@"MyNextViewController" bundle:nil];
_myNextViewController.myViewControllerArray = self.myViewControllerArray;
...

在第二种方法中,您可以在应用程序委托中创建 myAppDelegateArray 属性,在应用程序初始化时实例化数组(或根据需要实例化其他地方).

In the second approach, you could create a myAppDelegateArray property in your application delegate, instantiating the array when the application initializes (or instantiated somewhere else, on demand).

然后可以从任何类(包括视图控制器)中调用此属性的getter.

You can then call the getter for this property from any class — including view controllers.

例如,在 MyNextViewController 的实例中,您可能具有一个名为 myViewControllerArray 的属性,并将其设置如下:

For example, within an instance of MyNextViewController, you might have a property called myViewControllerArray and you would set it as follows:

self.myViewControllerArray = [UIAppDelegate myAppDelegateArray]; 

您将在应用程序常量文件中的某个位置添加 #define 语句,例如:

You would add a #define statement somewhere in your application constants file, e.g.:

#define UIAppDelegate ((MyAppDelegate *)[UIApplication sharedApplication].delegate)

或根据需要使用完整的 [UIApplication sharedApplication] .delegate 调用.

or use the full [UIApplication sharedApplication].delegate call, if you prefer.

作为一种通用方法,人们似乎更喜欢应用程序委托方法,因为它分散了对所需属性的访问权限.

As a general approach, people seem to prefer the app delegate approach, as it decentralizes access to the desired property.

使用这种方法,如果您重新布置视图控制器或将新的视图控制器插入VC层次结构,则无需调试从父视图控制器继承的子视图控制器属性,因为始终可以从应用程序委托获得引用

With this approach, if you rearrange your view controllers or insert new view controllers into your VC hierarchy, you wouldn't need to debug child view controller properties inherited from parent view controllers, because a reference is always available from the app delegate.

这篇关于如何正确地从一个UIViewController传递NSArray/NSMutableArray到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆