两界面间传值方法总结

来源:互联网 发布:尺八制作数据 编辑:程序博客网 时间:2024/05/21 22:25

以下以viewB传值给viewA 为例

1)属性传值 @interface和@implemented

方法:在viewA的属性中声明变量,在viewB中声明、定义viewA,并将值传递给viewA的属性值。

2)protocol 和 delegate 回调函数传值(该方法只适合界面上下层的传值)

方法:在viewA中@protocol viewAControllerDelegate 定义方法,并在 .m 文件中实现该方法(viewA需要继承改delegate)。在viewB中定义viewAControllerDelegate 实例,并通过该delegate传递值给viewA 。

说明:delegate只是一种较为简单的回调,且主要用在一个模块中,例如底层功能完成了,需要把一些值传到上层去,就事先把上层的函数通过delegate传到底层,然后在底层call这个delegate,它们都在一个模块中,完成一个功能,例如说 NavgationController 从 B 界面到A 点返回按钮 (调用popViewController方法可以用delegate比较好。

3) iOS开发中使用[[UIApplication sharedApplication] openURL:] 加载其它应用

描述:在iOS开发中,经常需要调用其它App,如拨打电话、发送邮件等。UIApplication:openURL:方法是实现这一目的的最简单方法,该方法一般通过提供的url参数的模式来调用不同的App。

方法:例如调用谷歌地图(Google Maps)

NSString *addressText = @"7 Hanover Square, New York, NY 10004";  addressText = [addressText stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding];  NSString* urlText = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@", addressText];  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlText]]; 

SharedApplication相当于一个全局变量 [UIApplication UISharedApplication].delegete

AppDelegate *delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;MyTabBarViewController *tabBar = (MyTabBarViewController*)delegate.window.rootViewController;[firstShowFeed addSubview:feedBackgroundView];[tabBar.view addSubview:firstShowFeed];

4) NSUserDefaults读取和写入自定义对象

方法:

NSString *string = [NSString stringWithString @"data is here"];    NSUserDefaults *data = [NSUserDefaults standardUserDefaults];    [data setObject:string forKey:@"key"];    NSString *value;    value = [data objectForKey:"key"];    

说明:NSUserdefault这个是一个字典,经常用来存储用户名和密码。但是传多次时候有可能覆盖前面的内容。而且并不是所有的东西都能往里放的。

NSUserDefaults只支持: NSString, NSNumber, NSDate, NSArray, NSDictionary.

5)NSNotificationCenter传值

方法:

说明:两个模块之间联系不是很紧密,就用notification传值,例如多线程之间传值用notificaiton。

6)单例传值

方法:在oc中要实现一个单例类,至少需要做以下四个步骤:

1、为单例对象实现一个静态实例,并初始化,然后设置成nil,

2、实现一个实例构造方法检查上面声明的静态实例是否为nil,如果是则新建并返回一个本类的实例,

3、重写allocWithZone方法,用来保证其他人直接使用alloc和init试图获得一个新实力的时候不产生一个新实例,

4、适当实现allocWitheZone,copyWithZone,release和autorelease

说明:单例这个也相当与全局的变量,viewA、viewB都可以设置并传递单例中的值。单例模式就是只有一个实例,确保一个类只有一个实例,并且自行实例化并向整个系统提供这个实例,一个单例类可以实现在不同的窗口之间传递数据。





参考文章:

1、(总结)http://justcoding.iteye.com/blog/1451948

2、http://blog.csdn.net/niitlcj/article/details/7498022

3、(delegate)http://blog.sina.com.cn/s/blog_5e730c7d01010k7y.html

4、http://www.cocoachina.com/bbs/read.php?tid=76331

5、http://blog.csdn.net/tangren03/article/details/7915045

5、(总结)http://hi.baidu.com/qiqizones/item/a458e1c9b63400f7964452ca

6、(单例传值)http://jobleeimay.blog.163.com/blog/static/212532289201302473652537/

原创粉丝点击