开发者

NSMutablearray set to (null)?

开发者 https://www.devze.com 2023-03-15 03:28 出处:网络
So i have two view controller in FirstViewController and SecondViewController in FirstViewController 开发者_StackOverflow社区 NSMutableArray *array;

So i have two view controller in FirstViewController and SecondViewController

in FirstViewController

开发者_StackOverflow社区
 NSMutableArray *array;

create a property for it and synthesised it

in SecondViewController

NSMutableArray *arraySecond;

create a property and synthesized it then I try to do something like this (after arraySecond is set to something like a b c d )

FirstViewController *FV = [[FirstViewController alloc]init];
FV.array = arraySecond;
[FV release];

I try to do that but when I try to print out the array from firstviewcontroller it is being set to (null) why is it doing that and what can i do to fix it?


FirstViewController *FV = [[FirstViewController alloc]init];

secondViewController *SV = [[secondViewController alloc]init];

//here create secondArray

[FV SetArray:SV.arraySecond];

If you synthesized the arraySecond then [self.arraySecond release];


You are creating an instance of FirstViewController, setting the value of array and then releasing that instance which will deallocate the object. So the entire effort is wasted. Since this is in the SecondViewController, I am assuming the FirstViewController exists by this time so you shouldn't be setting the array of a new instance of FirstViewController but try to pass it to the existing instance. Since you already have a property declared to share across the view controllers, we will make use of it.

Do this when instantiating the SecondViewController instance in FirstViewController,

SecondViewController * viewController = [[SecondViewController alloc] init];

self.array = [NSMutableArray array];
viewController.arraySecond = self.array;

[self.navigationController pushViewController:viewController animated:YES];
[viewController release];

Now the array is shared across the view controllers. Do not initialize the arraySecond property elsewhere so that both of them keep pointing to the same object and the changes your make to arraySecond are visible to the FirstViewController instance. After coming back to the FirstViewController instance, access the values you've added using array property.

Alternatives to object sharing are delegate mechanism and notifications. You can look into them too. For now, this should work.

0

精彩评论

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