如何在第二个viewController ios上将传递的值添加到NSMutableArray中

时间:2015-05-21 15:47:33

标签: ios nsmutablearray

在objective-c中,我创建了两个UIViewControllers FirstViewController和SecondViewController。在Storyboard中,我创建了一个从FirstViewController到SecondViewController的segue,然后在SecondViewController上按Ctrl键拖动到Exit,从而创建从SecondViewController到FirstViewController的unwind segue。

每次从FirstViewController到SecondViewController,我都会传递一个NSString,而在SecondViewController上,我有一个NSMutableArray,每次,当我从FirstViewController传递NSString后,我将它添加到NSMutableArray但是,经过几次来回,SecondViewController上的NSMutableArray只包含一个NSString。似乎每次返回到FirstViewController并返回到SecondViewController时,NSMutableArray重置为nil。

在FirstViewControll.m

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue.identifier isEqualToString:@"CamToPhotoReviewSegue"]) {
        SecondViewController *prc = (SecondViewController *) segue.destinationViewController;
        prc.photoName = photoNameToPhotoReviewController;
    }

}

One SecondViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.arrayOfPhotos = [[NSMutableArray alloc] init];
    // Push photo name into arrayOfPhotos
    [self.arrayOfPhotos addObject:photoName];
}

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

当您返回FirstViewController时,SecondViewController会从导航堆栈中弹出并取消分配,因为它已不再使用。当你再次回到SecondViewController时,它的一个新实例被推送到导航堆栈,因为它是一个新的"查看控制器正在查看由于NSMutableArray中包含您的字符串是SecondViewController的实例字段,因此在第二个视图控制器被取消分配时会被取消分配。

防止NSMutableArray被重置"每次都使用外部数据对象。数据对象将包含数组,FirstViewController将创建数据对象(在init中创建数组)。然后,当调用prepareForSegue时,FirstViewController需要将字符串添加到数据对象的数组中,然后将数据对象传递给SecondViewController,就像当前正在传递字符串一样

通过执行此操作,当secondViewController被取消分配时,数据对象(以及数组)也不会被删除,因为firstViewController仍在使用它。

//the data object's .h
@interface Data:NSObject
{
    NSMutableArray* array;
}
@end

//in FirstViewController
- (void)viewDidLoad
{
    //declare myData in the .h
    myData = [[Data alloc] init];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue.identifier isEqualToString:@"FirstToSecondSegue"])
    {
        SecondViewController* svc = (SecondViewController*)segue.destinationViewController;
        myData.array.addObject(myCoolString);
        svc.myData = myData;
    }
}

//in SecondViewController.h
@interface SecondViewController:UIViewController
{
    Data* myData;
}
@end