Xcode: Storyboard Tabbed Application Passing Data

2019-01-20 03:48发布

问题:

I am currently using the following code to try to pass the text in a UITextField between 3 view controllers that are looking at the same ViewController.h and ViewController.m files:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"NameOfSegue"]) {
        ViewController *ibcVC = segue destinationViewController;
        ibcVC.myTextField = self.myTextField;
    }
}

I have 3 view controllers linked in the following order: ViewC1 => ViewC2 => ViewC3.

My UITextField is on ViewC2.

When I click on the button on ViewC2 for example, that Pushes in ViewC3, it passes the data just fine to ViewC3. However, say I am currently on ViewC2, I type something in the UITextView, and I next click on the Back button on the Navigation that Xcode automatically puts there when working with tabbed view applications, it will take me to ViewC1 just fine as expected. However, if I push the button on ViewC1 that Pushes in ViewC2, the Data/Text I typed in my UITextField has been erased or reset to null.

So basically here is the problem using a slight digital visual:

DATA IS PUSHED CORRECTLY EX.

ViewC1 => ViewC2 => ViewC3

DATA IS ERASED IF WE PRESS THE BACK BUTTON ON NAVIGATION EX.

ViewC1 <= ViewC2

回答1:

One solution is to store your string in a singleton.

SharedStrings.h =

#import <Foundation/Foundation.h>

@interface SharedStrings : NSObject{
    NSString *string;
}

+(SharedStrings *)sharedString;
-(void)setString:(NSString *)newString;
-(NSString *)getString;

@end

SharedStrings.m =

#import "SharedStrings.h"

static SharedStrings *sharedString;

@implementation SharedStrings

-(id)init{

    self = [super init];
    string = [NSString new];
    return self;
}

+(SharedStrings *)sharedString{
    if (!sharedString) {
        sharedString = [[SharedStrings alloc] init];
    }
    return sharedString;
}

-(void)setString:(NSString *)newString{
    string = newString;
}
-(NSString *)getString{
    return string;
}

@end

You could then have all your views get and set the string as necessary, like so:

- (void)viewWillAppear:(BOOL)animated
{
    [myTextField setText:[[SharedStrings sharedString] getString]];
    [super viewWillAppear:animated];
}

-(void)textFieldDidEndEditing:(UITextField *)textField{

    if (textField == enterInfoTF) {
        [[SharedStrings sharedString] setString:textField.text];
    }
}