How to properly pass NSArray / NSMutableArray from one UIViewController to another

痞子三分冷 提交于 2019-12-25 04:53:43

问题


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 ...

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?

Thanks


回答1:


There are two approaches, generally speaking.

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;
...

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).

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

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]; 

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

#define UIAppDelegate ((MyAppDelegate *)[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.

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.




回答2:


you are probably not retaining it, it gets deallocated and you are trying to access it again. try to send a [myArray retain] where you are using it (in each of the controllers), and [myArray release] when you are done with it



来源:https://stackoverflow.com/questions/2648851/how-to-properly-pass-nsarray-nsmutablearray-from-one-uiviewcontroller-to-anoth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!