在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];
}
有人可以帮忙吗?
答案 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