Objective

一、创建方法:

二、实现过程:

     1、遵循协议:

          @protocol NurseWorkingProtocol <NSObject>   //<> 表示遵守协议,创建时就有(NurseWorkingProtocol.h中)

     2、协议内容:(NurseWorkingProtocol.h中)

         @required  // 必须做的,默认

         - (void)cleanHouse;

         @optional  // 可选的

         - (void)cook;

      3、指定遵循协议的人:(Nurse.h中)

           @interface Nurse : NSObject <NurseWorkingProtocol>   // 遵守协议

      4、完成协议指定的内容:(Nurse.m中实现)

           - (void)cleanHouse {

              NSLog(@"打扫房间!");

          }

          - (void)cook {

              NSLog(@"做饭");

          }

三、代理委托:(用Custom找Business买iPhone举例)

     1、创建协议:(Custom.h中)

@protocol CustomDelegate <NSObject>

- (void)buyIphone:(NSString *)iphoneType;

@end

     2、设置代理人:

@property (nonatomic,weak) id<CustomDelegate> delegate;  // 必须遵守协议

     3. 找代理人,见Business.h中遵守协议,并在Business.m中实现协议中的方法

@interface Business : NSObject <CustomDelegate>
- (void)buyIphone:(NSString *)iphoneType {
    
    NSLog(@"%@有货,我帮你买手机", iphoneType);
}

     4、上述一切准备就绪,就可以开始买手机啦:(Custom.h中声明方法,在Custom.m中实现如下)

 
- (void)beginBuy {
    
    //   找到代理人                代理人实现了代理方法,响应方法
    if (self.delegate && [self.delegate respondsToSelector:@selector(buyIphone:)]) {
        [self.delegate buyIphone:@"iphone7"];
        
    }else {
        NSLog(@"代理人不存在或者代理人没有实现代理方法");
    }
}

     5、在main函数中分别定义一个Custom和Business对象,将Custom对象的代理给business,即找到代理人,然后开始:

           custom.delegate = business;  // 找到代理人

           [custom beginBuy];           // 开始买

四、通知

     1、发布通知:(main.m)

 // 1. custom 发布通知              通知的关键标志 name 用于标识后面接收该通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"buyIphone" object:@"iphone7"];

     2、添加观察:(Business.m)

- (instancetype)init {
    
    self = [super init];

    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification:) name:@"buyIphone" object:nil];
    }
    return self;
}
- (void)notification :(id)noti { id obj = [noti valueForKey:@"object"]; // ValueForkey 因为是kvc的 NSLog(@"noti = %@", noti); NSLog(@"object = %@", obj); } - (void)dealloc { // [[NSNotificationCenter defaultCenter]removeObserver:self]; // 移除所有通知 [[NSNotificationCenter defaultCenter]removeObserver:self name:@"buyIphone" object:nil]; // 移除单条通知 因为是在ARC状态下,所以没有[super dealloc] }

五、总结:

         1. 协议只有声明文件

         2. 在遵守协议的类中导入协议的文件,并添加遵守协议  在@interface 后面加尖括号遵守协议

         3. @required 必须在.m 中实现, @option 可以不用实现,也即遵守协议做事情

         4. 原本类(Nurse.h)中 写@interface Nurse : NSObject <NurseWorkingProtocol>

         

         委托代理

         5. 可以单独写一个文件,如上所述,还可以在类中直接写 @protocal 见“代理委托”

         6. 对象类型后面加了<协议名>, 则该对象一定得是遵守了这个协议的对象

         7. 设置代理人的时候,要用弱引用(weak),而且要遵守过协议的对象才能成为代理人

         8. 委托代理使用了回调机制

         

         通知

         1. 注册接收通知的观察着

         2. 发送通知(postNotification)   ---   接收通知(addObserve)

         3. 移除通知 (dealloc 中 remove)

 

原文地址:https://www.cnblogs.com/ciciCassie/p/5796793.html