简体   繁体   中英

how to pass a string value from one view controller to another view controller

hi i am new to objective c. i have a login view controller with .h, .m, .xib files. and after successful login i need to go to the second page.

The scenario is this, i am accessing web services. to authenticate the user, i send the username and password to the web service and in return i get a string value. based on the results of the string value i need to display a second screen. Please help

If you only need to pass just a few values you can make them parameters to the init method. For example:

-(id)initWithUserName:(NSString *)name andPassword:(NSString *)password {
    self = [super init];
    if (nil == self) {
        return nil;
    }

    // display or store login info somewhere
    [someLabel setText:name];

    return self
}

Otherwise if you have a lot of values you want to use in the next view go with Morion's advice and make a separate class.

You can create a class to store some shared data and create an instance of it in your application delegate. in such way you can use this shared data in any class of your app.

OPNe way is to create properties in the app delegate. Each controller can access the appdelegate with:

[[UIApplication sharedApplication] delegate]

Is this your questions; when you get your response from the server, you need to make a view controller and put that string into it?

Try something like this in your first view controller

// Get the string from the server
NSString *string = [get string from server];

// Create the second controller
SecondViewController *controller = [[SecondViewController alloc] initWithNibName:@"nibname" bundle:nil];

// Set the text property of a label in the controller
controller.myLabel.text=string;

// Add the view to the window so we can see it
[[[[UIApplication sharedApplication] delegate] window] addSubview:controller.view];

This will create a new controller, set a string in it and display it in the window.

You will need to make a xib file that contains a UILabel and attach it to a propety called myLabel in the second controller ie

@interface SecondViewController {
  UILabel *myLabel;
}

@property (nonatomic, retain) IBOutlet UILabel *myLabel;

@end

Hope this helps,

Sam

You can't display values in nib files.

Get a reference to the Standard user defaults and store the string in there. Then you'll have access to the value wherever you want.

NSString *str1 = @"Apple";
NSString *str2 = @"Orange";

if([str1 isEqualToString: str2]) {

}else{

}

it will help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM