Printing vc1 NSString from vc2



我想打印vc1。String1 from vc2.

当前控制台显示:

vc1。string1 (null)

当我不使用storyboard时,我像这样访问vc1变量:

AppDelegate *appDelegate = [(AppDelegate *)[UIApplication sharedApplication]delegate];
NSLog(@"vc1.string1 %@", appDelegate.viewController.string1);

但是我不知道如何访问vc1。字符串,当我使用storyboard

请帮忙谢谢。

注:这是我的项目链接:http://dl.dropbox.com/u/12439052/AccessDiffClass.zip

//ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
    NSString *string1;
}
@property (nonatomic, strong) NSString *string1;
@end
#import "ViewController.h"
@implementation ViewController
@synthesize string1;
-(void)viewDidLoad {
    string1 = @"String One";
    NSLog(@"string1 %@", string1);
}
@end

趋势:

//ViewController2.h
#import <UIKit/UIKit.h>
@class ViewController;
@interface ViewController2 : UIViewController {
    ViewController *vc1;
}
@property (nonatomic, strong) ViewController *vc1;
@end
#import "ViewController2.h"
#import "ViewController.h"
@implementation ViewController2
@synthesize vc1;
-(void)viewDidLoad {
    NSLog(@"vc1.string1 %@", vc1.string1);
}
@end

我下载了你的项目并将这段代码添加到你的ViewController中。m文件:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSLog( @"preparing for segue" );
    ViewController2 * vc2 = [segue destinationViewController];
    vc2.vc1 = self;
}

这得到的东西出现在我的模拟器控制台的希望。

现在,显然不是最好的做法。在ARC的世界里,我不知道vc1是否被保留,或者我们是否在泄漏。这将是聪明得多你给你的ViewController2类一个NSString *属性,在prepareForSegue方法中设置。同时给segue一个标识符

这是另一个关于prepareForSegue的StackOverflow问题,更多(更详细)。

上次犯了一个错误。

关键代码:appDelegate = (appDelegate *)[[UIApplication sharedApplication] delegate];vc1 = appDelegate.viewController;NSLog(@"string1 %@", vc1.string1);

http://dl.dropbox.com/u/12439052/passingValue.zip

最新更新