Naresh Venkat
Naresh Venkat

Reputation: 319

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

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?

Upvotes: 4

Views: 12187

Answers (4)

Kingsley Mitchell
Kingsley Mitchell

Reputation: 2589

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]()

Upvotes: 0

makboney
makboney

Reputation: 1824

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

Upvotes: 3

Axel
Axel

Reputation: 966

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.

Upvotes: 1

Abdurrashid Khatri
Abdurrashid Khatri

Reputation: 338

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

Upvotes: 0

Related Questions