Objective-C 通知

创建一个老师类 和 学生类   实现通知

/**
 * 老师类
 * Teacher.h
 *
 */
#import <Foundation/Foundation.h>

@interface Teacher : NSObject

//这里设置成单例 以为只有一个老师发通知
+ (Teacher *)sharedTeacher;

//老师发通知
- (void)sendMessage;

@end

/**
 *  Teacher.m
 */

#import "Teacher.h"
static Teacher *t = nil;

@implementation Teacher

+ (Teacher *)sharedTeacher
{
    if (t == nil) {
        t = [[Teacher alloc] init];
    }
    return t;
}


- (void)sendMessage
{
    
    //注册通知 中心  [[NSNotificationCenter defaultCenter]
    //发通知   - (void)postNotificationName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"mmff" object:self userInfo:@{@"notice":@"十月一日放假 7天"}];
}

@end



/**
 * 学生类
 * Student.h
 */
#import <Foundation/Foundation.h>

@interface Student : NSObject

//接收通知
- (void) receiveMessage;

@end


/**
 *  Student.h
 *
 */
#import "Student.h"

@implementation Student

- (void)receiveMessage
{
    //注册通知中心   然后响应通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hoppy:) name:@"mmff" object:nil];
}


//响应通知
- (void)hoppy:(NSNotification *)notice
{
    NSDictionary *d = [notice userInfo];
    NSLog(@"%@",[d objectForKey:@"notice"]);
}

//移除通知
- (void)dealloc
{
    //移除某个通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"mmff" object:nil];
    
    //移除所有通知
    //[[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end



/**
 *  Student.h
 *
 */
#import "Student.h"

@implementation Student

- (void)receiveMessage
{
    //注册通知中心   然后响应通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hoppy:) name:@"mmff" object:nil];
}


//响应通知
- (void)hoppy:(NSNotification *)notice
{
    NSDictionary *d = [notice userInfo];
    NSLog(@"%@",[d objectForKey:@"notice"]);
}

//移除通知
- (void)dealloc
{
    //移除某个通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"mmff" object:nil];
    
    //移除所有通知
    //[[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

你可能感兴趣的:(Objective-C 通知)