标签:blog io os ar 文件 sp div c on
声明一个协议头文件
#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
标签:blog io os ar 文件 sp div c on
原文地址:http://www.cnblogs.com/wangweixl/p/4011915.html