Objective-C_语言_NSNotification(通知)

本文介绍了Objective-C中使用NSNotification进行观察者设计模式的实现。通过创建NSNotification对象,利用NSNotificationCenter的单例发送和接收通知,详细展示了如何在不同类中注册监听器、发送通知以及处理通知。同时,给出了Student、Weather和PhoneUser类的示例,演示了在实际场景中如何应用通知机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ViewController.m
#import "ViewController.h"
#import "Student.h"
#import "Weather.h"
#import "PhoneUser.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    /*
     通知 NSNotification
     
     通过学习我们的KVO是一种简单的观察者设计模式,涉及到两个对象,分别是 观察者和被观察者。这种方式是实质
     有很大的局限性,那么OC
     的‘Foundation’框架又为开发者提供了新的一种观察者设计模式,即“通知”
     通知,是一种发送给一个或多个观察者,用来通知其在程序中发生了某个事件的消息
     。cocoa中的通知机制遵循的是一种广播模式。它是一种程序中事件的发起者或者处理者和其他想要
     字典该事件的对象沟通的一种方式,消息的接收者,也就是观察者想应该事件来改变自己的UI 行为或状态
     
     
     在OC中,使用'NSNottification'类来表示一个通知
     
     
     */
    //初始化一个‘NSNottification’的实例对象
    NSNotification *notification1=[NSNotification notificationWithName:@"通知名称1"
                                                                object:self];//object通知的发起者
    NSNotification *notification2=[NSNotification notificationWithName:@"通知名称2"
                                                                object:self
                                                              userInfo:@{@"content":@"hello world"}];
    /*
     其中 
     1.name:通知的名称,最后用英文,用来识别通知对象
     2.object:表示通知的发起人
     3.userInfo:表示通知的内容
     */
    
    
    /*
     这个通知就行显示中的邮件,邮件都需要邮局发送给接收者。在OC中也一样,‘Foundation’
     框架定义了一个单例,通知中心,NSNottificationCenter来统一发送通知的实例对象给观察者
     
     */
    //通知中心 单例类,拿到通知中心的单例
    NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
    
    /*
     
     建立通知发送机制,步骤如下:
     1.注册相关监听者,并实现监听到通知时的方法
     2.在需要的时候,被监听的对象取我们的通知中心发送通知
     3.在‘dealloc’方法中,移除通知
     
     */
    
    
    Student *student=[Student new];
    
    //通知中心发通知
    [center postNotification:notification2];//填对象
    
    Weather *weather=[Weather new];
    PhoneUser *phoneUser=[[PhoneUser alloc]init];
}

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

@end
================================================================
Student.h
#import <Foundation/Foundation.h>

@interface Student : NSObject


@end
=================================================================
Student.m
#import "Student.h"

@implementation Student

-(id)init
{
    if (self=[super init])
    {
        //注册监听者
        //回调监听者
        //移除监听者
        //到我们的通知中行去让自己称为某个通知的监听对象
        /*
         1.要去接收通知的对象  addObserver
         2.接收通知响应的方法  selector
         3.接收通知的名称   name
         4.发起通知的对象,一般我们不需要知道,把它写成nil    object
         */
        [[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
==================================================================================================
Weather.h
#import <Foundation/Foundation.h>

@interface Weather : NSObject

-(void)sendMessage;

@end

====================================================================================================
Weather.m
#import "Weather.h"

@implementation Weather

-(void)sendMessage
{
    /*
     - (void)postNotification:(NSNotification *)notification;
     - (void)postNotificationName:(NSString *)aName object:(nullable id)anObject;
     - (void)postNotificationName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;
     */
    [[NSNotificationCenter defaultCenter] postNotificationName:WeatherAndPhoneUser
                                                        object:self
                                                      userInfo:@{@"weather":@"Sunny"}];
}

@end
===================================================================================================
PhoneUser.h
#import <Foundation/Foundation.h>

@interface PhoneUser : NSObject

@end
===================================================================================================
PhoneUser.m
#import "PhoneUser.h"

@implementation PhoneUser

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

-(void)nottificationAction:(NSNotification *)nottification
{

    NSDictionary *dictionary=nottification.userInfo;
    NSLog(@"今天的天气:%@",dictionary[@"weather"]);

}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:WeatherAndPhoneUser object:nil];
}

@end

==============================================================================
在Xcode里面按快捷键->com+N->在左面OS X下面的Other->PCH File->按Next
在Supporting Files在新建PCH File
然后点击左面最左面上面工程项蓝色标志的那个,在中间窗口上方会有Build Settings这个选项,在下面找到Apple LLVM7.0 - Language
下面找到Profix Header  右边点击一下会出现文本框然后打上:$(SRCROOT)/工程名/(PrefixHeader.pch)文件名
#ifndef PrefixHeader_pch
#define PrefixHeader_pch

// Include any system framework and library headers here that should be included in all compilation units.
// You will also need to set the Prefix Header build setting of one or more of your targets to reference this file.


//宏定义

#define WeatherAndPhoneUser @"weatherAndPhoneUser"//宏定义不用=号和;



#endif /* PrefixHeader_pch */

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值