如何设置和传递在另一个View Objective C中也可访问的变量值

时间:2016-03-05 07:16:52

标签: ios objective-c

在AppDelegate.h中

InvalidCastException

在ViewController.m中

@property(strong,nonatomic)NSString *str2;

输出:你好

Tableview中的导航代码didselect方法(视图控制器): -

AppDelegate *c3=[[AppDelegate alloc]init];
c3.str2= @"Hello";

NSLog(@"Output:-%@",c3.str2);

在Class2.m中: -

Class2  *c2=[self.storyboard instantiateViewControllerWithIdentifier:@"cl2"];
[self.navigationController pushViewController:c2 animated:YES];

输出:-null

2 个答案:

答案 0 :(得分:5)

首先,让我们修复您当前的方法:一些人建议使用app delegate来存储共享值的原因是有一个易于访问的实例。您永远不会创建新的应用代理,而是访问共享代码:

AppDelegate *c3 = (AppDelegate*)[[UIApplication sharedApplication] delegate];

使用上述内容替换[[AppDelegate alloc]init]后,您的代码将按照您期望的方式开始工作。

但是,这种解决方案并不理想。 App委托不应该是存储共享值的地方;它们应存储在模型对象中(如" M"在MVC中,模型 - 视图 - 控制器)。 Create a singleton model object,在其中放置共享变量,并通过访问来自不同视图控制器的单例来使用该共享变量。

答案 1 :(得分:2)

AppDelegate.h

@property(strong,nonatomic) NSString *str2;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    _str2 = "Hello"
}

ViewController.m以及任何其他想要访问str2的视图控制器中:

AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
NSLog(@"Output: %@", delegate.str2);

永远不要自己创建AppDelegate个对象。而是通过sharedApplication访问其实例。