记录下 iOS 不同场景/页面下数据传递常用的方法
一、使用属性
最简单常用的方法之一,用于从上到下的顺序,比如 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];
}
实现 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]);
}