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

如何在第二个viewController ios上将传递的值添加到NSMutableArray中,ios,nsmutablearray,Ios,Nsmutablearray,在objective-c中,我创建了两个UIViewControllerFirstViewController和SecondViewController。在故事板中,我创建了一个从FirstViewController到SecondViewController的序列,然后按住ctrl键并拖动SecondViewController上的按钮以退出以创建从SecondViewController到FirstViewController的展开序列 每次从FirstViewController传递到Se

在objective-c中,我创建了两个
UIViewController
FirstViewController和SecondViewController。在故事板中,我创建了一个从FirstViewController到SecondViewController的序列,然后按住ctrl键并拖动SecondViewController上的按钮以退出以创建从SecondViewController到FirstViewController的展开序列

每次从FirstViewController传递到SecondViewController时,我都会传递一个NSString,在SecondViewController上,我有一个
NSMutableArray
,每次从FirstViewController传递
NSString
,我都会将它添加到
NSMutableArray
,但是,来回几次之后,SecondViewController上的
NSMutableArray
仅包含一个NSString。似乎每次回到FirstViewController和SecondViewController时,
NSMutableArray
都会重置为零

关于FirstViewControll.m

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

}
一秒钟的viewcontroller.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];
}

有人能帮忙吗?

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

要防止每次“重置”NSMutableArray,请使用外部数据对象。数据对象将包含数组,并且
FirstViewController
将创建数据对象(在
init
中创建数组)。然后,当调用
prepareforsgue
时,
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

请发布代码您可能正在第二视图控制器中初始化阵列。创建一个静态变量来代替它看起来是一个更好的解决方案,我会试试。谢谢