通过使用NSNotification通知类,可以实现一对多的传递关系,同时也能很好的避免类与类之间层层递进的关系。但是必须记得在使用过程中可能出现通知会被多次接收,并执行相关的方法,避免这种情况出现必须在接收通知前先移除要接收的通知。
步骤1 创建通知类的公共类
.h文件
//
// NotificationManager.h
// DemoNotification
//
// Created by zhangshaoyu on 14-7-11.
// Copyright (c) 2014年 zhangshaoyu. All rights reserved.
// 功能描述:通知模式使用公用类
#import <Foundation/Foundation.h>
// 定义通知名称
static NSString *const NameNotification = @"NameNotification";
@interface NotificationManager : NSObject
/// 发送通知
+ (void)notificationSendWithName:(NSString *)name userInfo:(id)infoObj;
/// 接收通知
+ (void)notificationReceiveWithName:(NSString *)name delegate:(id)delegate selector:(SEL)selector;
/// 移除通知
+ (void)notificationRemoveWithName:(NSString *)name delegate:(id)delegate;
@end
/*
注意:在接收通知的过程中,必须先移除通知后再接收通知,否则会造成多次接收通知。
*/
.m文件
//
// NotificationManager.m
// DemoNotification
//
// Created by zhangshaoyu on 14-7-11.
// Copyright (c) 2014年 zhangshaoyu. All rights reserved.
//
#import "NotificationManager.h"
// 定义宏
#define NotificationShareManager [NSNotificationCenter defaultCenter]
@implementation NotificationManager
// 发送通知
+ (void)notificationSendWithName:(NSString *)name userInfo:(id)infoObj
{
// 发出通知的方法
// 方法1
// [NotificationShareManager postNotificationName:name object:nil];
// 方法2
// NSNotification *notification = [NSNotification notificationWithName:name object:nil];
// [NotificationShareManager postNotification:notification];
// 方法3
[NotificationShareManager postNotificationName:name
object:nil
userInfo:infoObj];
}
// 接收通知
+ (void)notificationReceiveWithName:(NSString *)name delegate:(id)delegate selector:(SEL)selector
{
// 接收通知前先移除通知,避免多次接收相同的通知
[self notificationRemoveWithName:name delegate:delegate];
[NotificationShareManager addObserver:delegate
selector:selector
name:name
object:nil];
}
// 移除通知
+ (void)notificationRemoveWithName:(NSString *)name delegate:(id)delegate
{
[NotificationShareManager removeObserver:delegate
name:name
object:nil];
}
步骤2 使用
// 发送通知
[NotificationManager notificationSendWithName:NameNotification userInfo:nil];
// 接收通知
[NotificationManager notificationReceiveWithName:NameNotification delegate:self selector:@selector(notificationAction:)];
// 响应通知
- (void)notificationAction:(NSNotification *)notification
{
NSLog(@"receive notification");
}
http://download.csdn.net/detail/potato512/7621713