您的位置:首页 > 其它

自定义通知的方法

2015-12-19 17:51 453 查看
<pre name="code" class="objc">#import <Foundation/Foundation.h>

@interface Student : NSObject

@en


#import "Student.h"

@implementation Student

-(id)init
{
if (self = [super init])
{
//注册监听者
//到通知中心去让自己称为某个通知的监听对象
/*
1.要去接收通知的对象
2.接收通知响应的方法
3.接收通知的名称
4.发起通知的对象,一般我们不需要知道,把它写成nil
*/

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:@"通知名称2" object:nil];

}
return self;
}

//监听到通知后回调的方法
-(void)notificationAction:(NSNotification *)notification
{
NSLog(@"Student收到 %@",notification.userInfo);
}

//移除监听者
-(void)dealloc
{
//移除某个通知的监听者
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"通知名称2" object:nil];

//移除所有通知的监听者
//    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

@end


#import <Foundation/Foundation.h>@interface PhoneUser : NSObject@end


#import "PhoneUser.h"

@implementation PhoneUser

-(id)init
{
if (self = [super init])
{
//注册监听者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifaicationAction:) name:WeatherAndPhoneUser object:nil];

}
return self;
}
//接收通知回调的方法
-(void)notifaicationAction:(NSNotification *)notification
{
NSDictionary *dictionary = notification.userInfo;
NSLog(@"今天的天气%@",dictionary[@"weather"]);
}

//移除监听对象
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:WeatherAndPhoneUser object:nil];
}

@end
#import "ViewController.h"
#import "Student.h"
#import "Weather.h"
#import "PhoneUser.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

/*
通知  NSNotification
通过学习'KVO',我们发现'KVO'是一种简单的观察者设计模式,涉及到两个对象,分别是 观察者 和 被观察者。这种方式实质有很大的局限性,那么OC的'Foundation'框架又为开发者提供了新的一种观察者设计模式,即"通知"

通知,是一种发送给一个或多个观察者,用来通知其在程序中发生了某个事件的消息。Cocoa中的通知机制遵循的是一种广播模式。它是一种程序中事件的发起者或者处理者和其他想要知道该事件的对象沟通的一种方式。消息的接收者,也就是观察者相应该事件来改变自己的UI、行为或状态。

在OC中,使用'NSNotification'类来表示一个通知
*/

//初始化一个NSNotification 的实例对象
NSNotification *notification1 = [NSNotification notificationWithName:@"通知名称1" object:self];

NSNotification *notification2 = [NSNotification notificationWithName:@"通知名称2" object:self userInfo:@{@"content":@"hello world"}];

/*
其中
1.name:通知的名称,最好英文,用来识别通知对象
2.object:表示通知的发起人
3.userInfo:表示通知的内容
*/

//这个通知就像现实中的邮件,邮件都需要邮局发送给接收人。在OC中也一样,'Foundation'框架定义了一个单例,通知中心,NSNotificationCenter 来统一发送通知的实例对象给观察者

//通知中心  单例类,拿到通知中心的单例
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

Student *student = [Student new];

//通知中心发送消息
[center postNotification:notification2];

//    Student *student = [Student new];

/*
建立通知发送机制,步骤如下:
1.注册相关监听者,并实现监听到通知时的方法
2.在需要的时候,被监听的对象去通知中心发送通知
3.在'dealloc'方法中,移除通知
*/

Weather *weather = [Weather new];
PhoneUser *phoneUser = [[PhoneUser alloc]init];

[weather sendMessage];

}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: