1,协议文件 

@protocol NursePtotocol <NSObject>

 //保姆的协议方法

- (void)startToAmuseBaby;

 @end

 2,管理类(使用类)

@interface Baby : NSObject

{ //1,定义实例变量,即谁遵守协议,是对象。也就是说:谁充当保姆角色。《定义》

    id <NurseProtocol> delegate;

}

- (void)setDelegate:(id)newDelegate;

- (id)delegate;

- (void)crying;

@end

@implementation Baby

//设置访问方法

- (void)setDelegate:(id)newDelegate

{ delegate = newDelegate;//2,赋值代理。即:让谁当保姆。《赋值》}

- (id)delegate

{ return delegate;}

//孩子的行为方法(使用代理的方法)

- (void)crying

{ NSLog(@"孩子哭了");

    //4,(管理类) 使用协议方法《使用》

    [self.delegate startToAmuseBaby];

}

@end

3,充当代理类

@interface Women : NSObject

@end

@implementation Women

- (void)startToAmuseBaby

{//3,代理类,《实现》<委托方法,需要设计者手写代码的地方,也是苹果暴露出的委托方法(UI中常用)>

    NSLog(@"保姆已经去看孩子了");}

@end

int main(int argc, const char * argv[])

{

    @autoreleasepool {

        Baby *baby = [[Baby alloc] init];

        Women *women = [[Women alloc] init];

        //调用setter方法,赋值代理:让women遵从nurse协议

        [baby setDelegate:women];

        [baby crying];

            }

    return 0;

}

相关文章:

  • 2021-08-01
  • 2021-05-10
  • 2021-05-10
  • 2022-12-23
  • 2021-10-11
  • 2021-08-01
  • 2021-12-23
  • 2021-05-24
猜你喜欢
  • 2021-11-04
  • 2022-12-23
  • 2021-12-22
  • 2022-12-23
  • 2019-05-22
  • 2021-08-20
  • 2021-05-31
相关资源
相似解决方案