我做了一个很简单的故事板基础的项目有两个视图控制器。
我想简单地访问从VC2 VC1中声明的字符串。 然后,第二VC应该显示在一个按钮的按压在一个TextField的文本。
我不想使用委派 , 全局数据或全局变量和extern一个单独的类 。 相反,我读了很容易使用对方一个VC的引用,实现变共享。
对于下面显示我的代码时,Xcode没有抱怨,但我的问题是这样的 : 在NSLog的第二VC返回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