我用两个视图控制器制作了一个非常简单的基于故事板的项目。
我想简单地从 VC2 访问在 VC1 中声明的字符串。然后,第二个 VC 应在按下按钮后在文本字段中显示文本。
我不想使用委托、全局数据或全局变量的单独类和 Extern 。相反,我读到使用对另一个 VC 的引用很容易实现变量共享。
对于下面显示的代码,XCode 没有抱怨,但是我的问题是:第二个 VC 中的 NSLog 返回 null。
如果有人能告诉我如何修改代码以将字符串传递给第二个 VC/告诉我哪里出错了,我将不胜感激。
VC1 标头:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property NSString* textToPassToOtherVC;
VC1 实现:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize textToPassToOtherVC = _textToPassToOtherVC;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_textToPassToOtherVC = @"Here is some text";
NSLog (@"Text in VC1 is: %@", _textToPassToOtherVC);
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
@end
VC2 标头:
#import <UIKit/UIKit.h>
@class ViewController;
@interface ViewController2 : UIViewController
@property (nonatomic, strong) ViewController *received;
@property (strong, nonatomic) IBOutlet UITextField *textDisplay;
- (IBAction)textButton:(id)sender;
@end
VC2 实现:
#import "ViewController2.h"
#import "ViewController.h"
@interface ViewController2 ()
@end
@implementation ViewController2
@synthesize textDisplay;
@synthesize received;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewDidUnload
{
[self setTextDisplay:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (IBAction)textButton:(id)sender {
NSLog (@"Text in VC1 from VC2 is: %@", self.received.textToPassToOtherVC);
textDisplay.text = self.received.textToPassToOtherVC;
}
@end