开发者

How to pass an array from one view controller to another?

开发者_Go百科

I'm developing an application. In it I need to pass an array from one view controller to another view controller.

How can I do this?


you can do it by defining an array property in second viewcontrollers .h file like:

@interface SecondViewController : UIViewController 
@property(nonatomic, strong)NSArray *array;
@end

Now in FirstViewconrtoller just pass it

SecondViewController *controller = [[SecondViewController alloc]....]
controller.array = yourArray.//the array you want to pass


I wouldn't return directly the reference of the array using return _theArray;. It is usually a bad coding design to do so. A better solution to your problem would be:

In your first controller's .h file:

@interface FirstViewController : UIViewController
{
    NSArray *_theArray;
}

- (NSArray *)theArray;

In your first controller's .m file:

- (NSArray *)theArray
{
    return [NSArray arrayWithArray:_theArray];
}

And wherever you want in your second controller's code:

NSArray *fooArray = [firstControllerReference theArray];

Be aware that in this example, the references of the objects stored in fooArray are the same as the ones stored in theArray. Therefore, if you modify an object in fooArray, it will also be modified in theArray.


just declare them in .h file & assign them property nonatomic & retain then synthesize them. Now create object of class & access that array :) very simple :)


In swift you

The first Viewcontroller in the prepare

var yourArray = [String]()
yourArray.append("String Value")
   let testEventAddGroupsViewController = segue.destination as! 
TestEventAddGroupsViewController
        testEventAddGroupsViewController.testEvent = yourArray

In the second view controller as a global variable

var testEvent = [String]()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜