将数据传递到不同 ViewController 之间的数组

Passing Data to Array Between Different ViewControllers

我有 2 个视图控制器,分别命名为 viewController 和 secondViewController。我想获取数据并使用委托将其发送到 secondViewController。我在 secondViewController 中也有一个数组,当每个数据来自 VC1 时,它必须像这样存储数据;

segue1,第一个数据来了 -> arrayElements {firstData} segue2,第二个数据来了 -> arrayElements {firstData, secondData}

但是每次 secondViewController 进入屏幕时,它都会丢失以前的数据(来自以前的 segues 的数据)。这是我的代码;

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

正如我所说,每次我单击显示按钮进行转播时,我都丢失了之前在 ViewController2 中的所有数据。

我以前看过类似的问题,但大多数都是关于只传递一个数据。我很困惑。

如何使用委托存储这些数据而不丢失以前的数据。

您有一个导航控制器,因此当您从 firstViewController 继续显示 secondViewcontroller 时,它会将 secondViewcontroller 推送到导航堆栈。 当点击后退按钮返回到 firstViewController 时,它会从导航堆栈中弹出 secondViewController 并将被释放,因此之后不会有数据或视图。

您的代码的问题是您每次都在 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;
    }
    ...
}