Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

ios - Pass a value from one ViewController to another in Objective-C

I'm fairly new to Objective-C, programming. The one thing, I'm currently putting up with is passing a value from the first ViewController to the next one.

I've read this entry here and it didn't help me. Which is funny, since his answer has nearly 500 votes, so I must be the problem. What I did was the following.

I opened my PreviewViewController.m and added the following line #import "MainViewController.h" since I wanted to pass a value from the PreviewViewController to the `MainViewController. Then, when I switch the layouts ( which successfully works ) I want to pass a value.

MainViewController  *mainViewController     = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
mainViewController.userId                   = @"539897197";

As you can see, I want to pass the userId. For that, I also created a property in the MainViewController.h

@property ( nonatomic, strong ) NSString *userId;

Now, In my MainViewController.m I want to access the userId. But when I log it, the console tells me it is null. However, when I set the variable right before the NSLog it works, so it seems like the passing is the problem.

Additionally in the MainViewController.m I have the following line

@synthesize userId = _userId; 

but even when I removed that line and changed the NSLog to NSLog(@"%@",self.userId); the same problem occurred.

How can I successfully pass the variables? Which step am I doing wrong?

EDIT This is how I switch the layouts

UIViewController    *viewController         = [[MainViewController alloc]init];
MainViewController  *mainViewController     = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
mainViewController.userId                   = @"539897197";
[self presentViewController:viewController animated:YES completion:NULL];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why not create a custom initializer and pass it in that way? Something like

- (id)initWithUserId:(NSString *)aUserId {
    self = [super initWithNibName:@"MainViewController" bundle:nil];
    if (self) {
        self.userId = aUserId
    }
    return self;
}

Then you can just do:

MainViewController *mvc = [[MainViewController alloc] initWithUserId:@"1234"]
[self presentViewController:mvc animated:YES completion:nil];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...