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

橙三吉。 提交于 2019-12-18 07:21:51

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/5076878/iphone-sdk-how-do-i-pass-an-array-of-values-from-a-viewcontroller-onto-other-vi

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