以一种编程方式将数据从一个viewcontroller传递到现有的viewcontroller

时间:2013-07-22 07:02:35

标签: ios uiviewcontroller

最近我陷入了一个问题,所以我无法继续下一个编码部分。 有两个视图控制器(比如first.m和second.m),我想在不使用故事板的情况下将参数数据从一个视图控制器传递到另一个视图控制器。但对我来说棘手的部分是第二个视图控制器已经在AppDelegate.m文件中启动。

如果我在第一个视图控制器中使用某个导入头文件启动了第二个视图控制器,我可以传递数据,例如..

@import "Second.h"

Second *secondView = [[Second alloc] initWithNibName:@"SecondNib" bundle:nil];
secondView.someStringValue = @"passThisString";

但是,这个编码会产生一个新的第二个视图控制器,这不是我想要的。我发现有类似

的东西
myAppDelegate *appDelegate = (myAppDelegate *)[[UIApplication sharedApplication] delegate];

连接到AppDelegate.m文件。但经过几天的挣扎,我的大脑正在停电。请给我任何建议。有没有办法将数据传递给现有的视图控制器而不使用故事板?或通过AppDelegate到第二个视图控制器的任何方式。任何帮助将不胜感激

3 个答案:

答案 0 :(得分:2)

@ jazzed28您可以在不启动Second的情况下执行此操作。您只需访问已启动的Second即可。所以在Second中声明myAppDelegate.h作为property就像这样 -

@property (nonatomic, strong) Second *svc;

然后,只要你需要秒,你可以像这样访问 -

myAppDelegate *appDelegate = (myAppDelegate *)[[UIApplication sharedApplication] delegate];

appDelegate.svc

答案 1 :(得分:1)

在myAppDelegate中创建两个用于设置数据和从Appdelegate获取数据的类方法,您可以使用APpdelegate类名来访问这些方法。

 Setter method
 +(void)setGlobalString:(NSString *)stringgValue{
          [[NSUserDefaults standardUserDefaults] setObject:stringgValue forKey:@"globalValue"];
     // you can save string value here by using NSUserDefaults or any thing else

    }
Getter method
+(NSString *)getGlobalString{
        return [[NSUserDefaults standardUserDefaults] forKey:@"globalValue"];
    }

你可以调用像

这样的方法
[myAppDelegate setGlobalString:yourString];

NSString *str = [myAppDelegate getGlobalString];

答案 2 :(得分:1)

之前已经多次询问过这个问题,包括StackOverflow。 如果你花了一些时间寻找答案,你可能会找到this answer例如。

相关问题