Ios 如何设置和传递在另一个视图中也可访问的变量值目标C
在AppDelegate.h中Ios 如何设置和传递在另一个视图中也可访问的变量值目标C,ios,objective-c,Ios,Objective C,在AppDelegate.h中 @property(strong,nonatomic)NSString *str2; 在ViewController.m中 AppDelegate *c3=[[AppDelegate alloc]init]; c3.str2= @"Hello"; NSLog(@"Output:-%@",c3.str2); 输出:-您好 Tableview didselect方法(视图控制器)中的导航代码:- 在Class2.m中:- AppDelegate *c3=[[Ap
@property(strong,nonatomic)NSString *str2;
在ViewController.m中
AppDelegate *c3=[[AppDelegate alloc]init];
c3.str2= @"Hello";
NSLog(@"Output:-%@",c3.str2);
输出:-您好
Tableview didselect方法(视图控制器)中的导航代码:-
在Class2.m中:-
AppDelegate *c3=[[AppDelegate alloc]init];
NSLog(@"%@",c3.str2);
输出:-Null首先,让我们修复您当前的方法:一些人建议使用app delegate存储共享值的原因是它有一个易于访问的实例。您从不创建新的应用程序代理,而是访问共享的应用程序代理:
AppDelegate *c3 = (AppDelegate*)[[UIApplication sharedApplication] delegate];
一旦您将[[AppDelegate alloc]init]
替换为上述内容,您的代码将开始按照您期望的方式工作
然而,这种解决方案并不理想。App delegate不应该是存储共享值的地方;它们应该存储在模型对象中(在MVC中作为“M”,模型视图控制器),将共享变量放入其中,并通过从不同的视图控制器访问单例来使用该共享变量。在
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
访问其实例
AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
NSLog(@"Output: %@", delegate.str2);