标签:live const dag delegate elf release hang world person
什么是代理?
1.代理(委托):自己不亲身做,让别人做
2.定义了协议的类可以看作将协议定义的方法代理给了实现这些方法的类
boss h
#import <Foundation/Foundation.h> #import "Assisant.h" @interface boss : NSObject // 使用我这个对象必须遵守我的协议,如果没有会出现不匹配的情况 @property id<Assisant> delegate;//代理 nil oc给nil任何消息都没有问题 -(void)travel; @end
boss m
#import "boss.h" // 未命名分类 @interface boss() -(void)takePlane; -(void)bookTicket; -(void)bookHotel; -(void)liveHotel; @end @implementation boss -(void)travel // 私有方法的前项引用 { [self bookTicket]; [self bookHotel]; [self takePlane]; [self liveHotel]; } //代理 -(void)bookTicket { [self.delegate bookTicket]; } -(void)bookHotel { [self.delegate bookHotel]; } -(void)takePlane { NSLog(@"老板亲自坐飞机"); } -(void)liveHotel { NSLog(@"老板亲自住酒店"); } @end
Assisant h
#import <Foundation/Foundation.h> #import "Assisant.h" @interface Assistant : NSObject<Assisant> @end
Assisant m
#import "Assistant.h" @implementation Assistant -(void)bookTicket { NSLog(@"给订票公司打电话"); NSLog(@"订机票"); } -(void)bookHotel { NSLog(@"助理 去携程"); NSLog(@"助理 去酒店"); } @end
协议 用作限制代理
@protocol Assisant -(void)bookTicket; -(void)bookHotel; @end
main
#import <Foundation/Foundation.h> #import "boss.h" #import "Assistant.h" #import "person.h" int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... NSLog(@"Hello, World!"); boss* b=[[boss alloc]init]; person* p=[[person alloc]initWithName:@"zhangsan" andAge:25 andGender:"m"]; Assistant* ass=[[Assistant alloc]init]; b.delegate=ass; // b.delegate=ass; [b travel]; } return 0; }
标签:live const dag delegate elf release hang world person
原文地址:https://www.cnblogs.com/zhangqing979797/p/13227801.html