Parth Bhatt
Parth Bhatt

Reputation: 19479

iPhone SDK: How do I pass an array of values from a ViewController onto other ViewController?

I tried creating a method like below in SecondViewController:

-(void)setValue:(NSMutableArray*)array
 { 
      //NSMutableArray *newArray = [[NSMutableArray alloc] init];
      newArray = [array retain];
 }

and passing the value from FirstViewController using an object of SecondViewController named second:

[second setValue:existingArray];

existingArray is an NSMutableArray.

What could be wrong?

Upvotes: 1

Views: 2744

Answers (2)

Sorin Antohi
Sorin Antohi

Reputation: 6135

You could use a property instead of the setter you have there(which looks bad). Question is do you really need to do a copy on the array or a retain would be enough?

Create a NSMutableArray *myArray as a local variable in the SecondViewController. Add a property @property(nonatomic, retain) NSMutableArray *myArray; in the interface.

Synthesize it and to set it just call [mySecondViewController setMyArray:newArray];

If you have instantiated correctly the SecondViewController and if the array that you want to send is not nil then it should work.

if you do it like this:

-(void)setValue:(NSMutableArray*)array
 { 
      NSMutableArray *newArray = [[NSMutableArray alloc] init];
      newArray = [array mutableCopy];
 }

newArray would be a variable declared inside the SetValue method, after the program exits the setValue method, the newArray variable will not be accessible anymore. Also you leak memory because newArray is never released.

Upvotes: 0

Satya
Satya

Reputation: 3330

In the code you have set the array in the "second" object of a SecondViewController.

So you need to use that object for displaying the SecondeViewController, other wise how can it won't show the array.

Check the following code.

 //   In the FirstViewController

- (void)buttonClicked:(id)sender{

    SecondViewController *second = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle: nil];
 [second setValue:existingArray];
 [self.navigationController pushViewController:second animated:YES];
 [second release];

}

Here in the code I am assigning the data to the array in the "second" object and I am using that object to display the controller.

Regards,

Satya

Upvotes: 3

Related Questions