我有两个viewController,分别命名为viewController和我想获取数据并使用委托将其发送到secondViewController。另外,我在secondViewController中有一个数组,当每个数据来自VC1时,它必须存储数据,如;
segue1,第一个数据来了->arrayElements{firstData}segue2,第二个数据来了->arrayElements{firstData,secondData}
但是每次secondViewController进入屏幕时,它会丢失先前的数据(来自先前序列的数据)。这里是我的代码;
FirstViewController.h
@protocol CustomDelegate <NSObject>
-(void)passData: (NSString*)data_in;
@end
@interface FirstViewController : UIViewController
@property (strong, nonatomic) NSString *myData;
@property (nonatomic, weak)id<CustomDelegate>delegate;
@end
firstViewController.m(我只复制了必需的部分)
- (IBAction)sendButton:(UIButton *)sender {
SecondViewController *svc = [[SecondViewController alloc] init];
self.delegate = svc;
[self.delegate passData:self.myData];
}
SecondViewController.h
import things here..
@interface SecondViewController : UIViewController <CustomDelegate>
@property (strong, nonatomic) NSString *receivedData;
@property (strong, nonatomic) NSMutableArray* receivedDataArray;
@end
SecondViewController.m
//declerations, properties, lazy instantiation for array here
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:YES];
self.receviedDataLabel.text = self.receivedData;
}
-(void)passData:(NSString *)data_in{
self.receivedData = data_in;
[self.receivedDataArray addObject:data_in];
}
这里是视觉;http://i.hizliresim.com/ql8aj3.png
正如我所说的,每次我单击show按钮来segue时,我在ViewController2中丢失了所有以前的数据。
我读过以前的问题,但大多数都是关于传递一个数据。我很困惑。
我如何使用委托存储这些数据而不丢失先前的数据。
您的代码的问题是,您每次都在SendButton
操作中初始化一个新的SecondViewController
。
因此每次点击sendButton
时,svc.receiveddata
都是一个空(新)数组
考虑将svc
保留为局部变量,并只调用init
一次。
类似于:
在FirstViewController.h
中,添加此行:
@property (strong, nonatomic) SecondViewController *svc;
并将这些行添加到FirstViewController.m
- (IBAction)sendButton:(UIButton *)sender {
...
if(self.svc == nil){
self.svc = [[SecondViewController alloc] init];
self.delegate = self.svc;
}
...
}
您有一个导航控制器,因此当您从firstViewController中选择显示secondViewcontroller时,它会将secondViewcontroller推送到导航堆栈。当点击back按钮返回到firstViewController时,它从导航堆栈中弹出secondViewController并将被释放,这样之后就没有数据或视图了。