在Objective-C中将一个ViewController中的值传递给另一个ViewController [英] Pass a value from one ViewController to another in Objective-C
问题描述
我对Objective-C编程很新。我现在忍受的一件事是将第一个 ViewController
中的值传递给下一个。
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.
我在这里阅读此条目,但这对我没有帮助。这很有趣,因为他的回答有近500票,所以我一定是个问题。我做的是以下。
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.
我打开了我的 PreviewViewController.m
并添加了以下行 #importMainViewController.h
因为我想将 PreviewViewController
中的值传递给`MainViewController。然后,当我切换布局(成功工作)时,我想传递一个值。
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";
如您所见,我想传递userId。为此,我还在 MainViewController.h中创建了一个属性
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;
现在,在我的 MainViewController.m
I想要访问userId。但是当我记录它时,控制台告诉我它是 null
。但是,当我在 NSLog
之前设置变量时,它起作用,所以似乎传递是问题。
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.
另外在 MainViewController.m
我有以下行
@synthesize userId = _userId;
但即使我删除了该行并更改了 NSLog
到 NSLog(@%@,self.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];
推荐答案
为什么不创建自定义初始化程序并将其传递给办法?类似
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;
}
然后你就可以这样做:
MainViewController *mvc = [[MainViewController alloc] initWithUserId:@"1234"]
[self presentViewController:mvc animated:YES completion:nil];
这篇关于在Objective-C中将一个ViewController中的值传递给另一个ViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!