首页 > 代码库 > 协议练习
协议练习
声明一个协议头文件
#ifndef Dog_Play_h#define Dog_Play_h@protocol Play <NSObject>@required- (void)brak;- (void)tail;- (void)go;@end#endif
定一个persons类.
#import <Foundation/Foundation.h>#import "Play.h"@interface Person : NSObject@property (nonatomic, retain) id<Play> animal;- (void)palyWithPet;@end
#import "Person.h"@implementation Person- (void)palyWithPet;{ if(_animal!=nil) [_animal brak]; [_animal tail]; [_animal go];}@end
定义一个猫类
#import "Cat.h"@implementation Cat : NSObject - (void)brak{ NSLog(@"miao......miao");}- (void)tail{ NSLog(@"the dog is roking tail");}- (void)go{ NSLog(@"the dog is running");}@end
定义一个狗类
#import "Dog.h"@implementation Dog- (void)brak{ NSLog(@"wang......wang");}- (void)tail{ NSLog(@"the dog is roking tail");}- (void)go{ NSLog(@"the dog is running");}@end
主函数中运行,声明person对象,CAT对象,dog对象.然后让person中的annimal指向cat对象,运行person 实例方法playwithannimal,则方法类会调用协议中的那三个方法
#import "ViewController.h"#import "Person.h"#import "Cat.h"#import "Dog.h"#import "Play.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. Person * person = [[Person alloc]init]; Dog * cat =[[Dog alloc]init]; person.animal = cat; [person palyWithPet]; }- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}@end
协议练习
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。