您的位置:首页 > 移动开发 > IOS开发

iOS 通知传值

2015-12-13 17:04 471 查看
首先, 创建并发送通知

例如

将一个页面两个输入框的内容传递, 到另外一个页面, 再改页面合适的位置创建并发送通知

//通知传值

NSMutableDictionary *dic = [@{@"name1":self.text1.text,
@"name2": self.text2.text}mutableCopy];

[[NSNotificationCenter
defaultCenter]postNotificationName:@"gyq"
object:nil
userInfo:dic];

在需要的页面 注册通知通知

//注册观察者

[[NSNotificationCenter
defaultCenter]addObserver:self
selector:@selector(reciver:)
name:@"gyq"
object:nil];

- (void) reciver:(NSNotification *)noti {

self.text1.text = noti.userInfo[@"name1"];

self.text2.text = noti.userInfo[@"name2"];

NSLog(@"%@", noti.userInfo);
}

下面是对通知的一些详情介绍

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;
//observer:监听器,即谁要接收这个通知
//aSelector:收到通知后,回调监听器的这个方法,并且把通知对象当做参数传入
//aName:通知的名称。如果为nil,那么无论通知的名称是什么,监听器都能收到这个通知
//anObject:通知发布者。如果为anObject和aName都为nil,监听器都收到所有的通知

- (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block;
//name:通知的名称
//obj:通知发布者
//block:收到对应的通知时,会回调这个
//blockqueue:决定了block在哪个操作队列中执行,如果传nil,默认在当前操作队列中同步执行
通知
一个完整的通知一般包含3个属性:
- (NSString *)name; // 通知的名称
- (id)object; // 通知发布者(是谁要发布通知)
- (NSDictionary *)userInfo; // 一些额外的信息(通知发布者传递给通知接收者的信息内容)


初始化一个通知(NSNotification)对象:

- (instancetype)initWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo
+ (instancetype)notificationWithName:(NSString *)aName object:(id)anObject;
+ (instancetype)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;
发布通知:发布一个通知可以在notification对象中设置通知的名称、通知的发布者和额外信息等;

- (void)postNotification:(NSNotification *)notification;
- (void)postNotificationName:(NSString *)aName object:(id)anObject;
- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;


移除通知:

- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;


示例:在两个类之间传值

在接受类中注册通知监听器

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onChangeImage:) name:@"changeImage" object:nil];
实现监听回来的方法:

- (void)onChangeImage:(NSNotification*)sender
{
self.resultOKNumbers = sender.object;
self.dic = sender.userInfo;
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:@"确定提交本次绘画吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
alertView.tag = 100002;
alertView.delegate = self;
[alertView show];
}


上级界面发送通知:

[[NSNotificationCenter defaultCenter] postNotificationName:@"changeImage" object:text];
或者是传多个参数:

[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:text userInfo:dic];


当通知发出后就会执行监听的方法,在方法中通过sender.object获得传过来的对象,当需要传多个值的时候可以只用数组或者是字典作为传过来的对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: