IOS 不同场景/页面下数据传递方法
2015-10-20 15:29
423 查看
记录下 IOS 不同场景/页面下数据传递常用的方法
一、使用属性
最简单常用的方法之一,用于从上到下的顺序,比如 A >> B 时,传递A的数据到B。
二、使用 Protocol 协议
用于从下到上的顺序,比如 A >> B,再从 B back A 时,B的数据回传到A中。
.h 协议
B.h
B.m
A.h
实现 OtherDetegate 协议
A.m
三、使用 Notification Center 消息通知中心
可以用于跨场景的数据传递,比如 A 点击按钮,通知 C 开始下载。
通知中心可以同时向多个观察者传递数据
A.m
C.m
一、使用属性
最简单常用的方法之一,用于从上到下的顺序,比如 A >> B 时,传递A的数据到B。
OtherController *otherController = [OtherController new]; otherController.stringData = tfData.text; [self.navigationController pushViewController:otherController animated:YES];
二、使用 Protocol 协议
用于从下到上的顺序,比如 A >> B,再从 B back A 时,B的数据回传到A中。
.h 协议
#import <Foundation/Foundation.h> /** 协议 */ @protocol OtherDetegate <NSObject> @required // 必须实现的方法 /** * 返回 * @param backString 返回带的数据 */ - (void) backToFirst:(NSString *) backString; @optional // 可选实现的方法 @end
B.h
/** 协议 */ @property (nonatomic, assign) id<OtherDetegate> otherDetegate;
B.m
// 使用协议中的方法回传数据 if (self.otherDetegate) { [self.otherDetegate backToFirst:tfOther.text]; }
A.h
实现 OtherDetegate 协议
A.m
B *b = [B new]; b.otherDetegate = self; [self.navigationController b animated:YES]; // 实现协议中的方法 /** 返回待来的数据 */ - (void) backToFirst:(NSString *)backString { tfData.text = backString; }
三、使用 Notification Center 消息通知中心
可以用于跨场景的数据传递,比如 A 点击按钮,通知 C 开始下载。
通知中心可以同时向多个观察者传递数据
A.m
/** 发送消息通知 */ - (void) btnNotificationClick { NSDictionary *dictData = @{NOTIFICATION_KEY:tfOther.text}; [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_OTHER object:self userInfo:dictData]; }
C.m
- (void)viewDidLoad { [super viewDidLoad]; ...... [self addObserverToNotification]; } - (void) dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } ....... /** 添加通知消息监听 */ - (void) addObserverToNotification { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showNotificationCenter:) name:NOTIFICATION_OTHER object:nil]; } /** 显示通知内容 */ - (void) showNotificationCenter:(NSNotification *)notification { NSDictionary *dict = notification.userInfo; NSLog(@"通知内容:%@", [dict objectForKey:NOTIFICATION_KEY]); }
相关文章推荐
- iOS的管理机制
- 在ios下保存数据到plist
- ios 文件上传, post数据
- IOS读取项目中文件
- [转] ios打包IPA的各种问题和解决方法
- IOS-照相,相片选取
- ios 获取当前时间
- NSURLConnection的几种请求方式
- IOS 字体大全
- iOS使用系统API扫描二维码条形码&限制扫描区域
- iOS: SegmentControl 实现页面切换的四种方法
- iOS使用zbar以及AVFoundation实现二维码扫描
- IOS基本数据类型之枚举
- iOS--崩溃日志分析
- iOS之用NSTimer定时刷新按钮的文字,避免按钮闪烁的办法
- ios修改textField的placeholder的字体颜色、大小
- ios学习-oc类目
- iOS 8 使用CoreLocation定位配置
- Block - 4
- iOS 9-iPhone6s-iPadmini4企业证书信任