首页 > 其他 > 详细

协议1

时间:2015-11-10 20:50:55      阅读:210      评论:0      收藏:0      [点我收藏+]

//结构:

技术分享技术分享技术分享

//main.m

 1 #import <Foundation/Foundation.h>
 2 #import "Rent1.h"
 3 #import "Rent2.h"
 4 #import "Rent3.h"
 5 #import "Person.h"
 6 
 7 int main(int argc, const char * argv[]) {
 8     @autoreleasepool {
 9      
10         Person *xiaowang=[[Person alloc]init];
11         
12         Rent1 *r1=[[Rent1 alloc]init];
13         r1.name=@"Li";
14         Rent2 *r2=[[Rent2 alloc]init];
15         r2.name=@"叶良辰";
16         Rent3 *r3=[[Rent3 alloc]init];
17         r3.name=@"赵日天";
18         
19         xiaowang.obj=r1;
20         
21         [xiaowang needHouse];
22      
23     }
24     return 0;
25 }

//RentPototol.h《协议》

#import <Foundation/Foundation.h>

@protocol RentPototol <NSObject>
@optional
-(void)rentHouse;

@end

//Person.h

 1 #import <Foundation/Foundation.h>
 2 #import "RentPototol.h"
 3 @interface Person : NSObject
 4 
 5 @property(nonatomic,strong)NSString *myName;
 6 @property(nonatomic,assign)id<RentPototol> obj;
 7 
 8 -(void)needHouse;
 9 
10 @end

//Person.m

 1 #import "Person.h"
 2 #import "RentPototol.h"
 3 
 4 @implementation Person
 5 
 6 -(void)needHouse
 7 {
 8     if ([_obj respondsToSelector:@selector(rentHouse)]) {
 9         [_obj rentHouse];
10     }
11     else
12     {
13         NSLog(@"臣妾做不到呀!");
14     }
15 }
16 @end

//Rent1.h

#import <Foundation/Foundation.h>
#import "RentPototol.h"

@interface Rent1 : NSObject<RentPototol>
@property(nonatomic,copy)NSString *name;

@end

//Rent1.m

#import "Rent1.h"

@implementation Rent1

-(void)rentHouse
{
    NSLog(@"我是%@,我打电话找房源",_name);
}

@end

//Rent2.h

#import <Foundation/Foundation.h>
#import "RentPototol.h"

@interface Rent2 : NSObject<RentPototol>
@property(nonatomic,copy)NSString *name;

@end

//Rent2.m

#import "Rent2.h"

@implementation Rent2

-(void)rentHouse
{
    NSLog(@"我是%@,我打电话找房源",_name);
}

@end

//Rent3.h

#import <Foundation/Foundation.h>
#import "RentPototol.h"

@interface Rent3 : NSObject<RentPototol>

@property(nonatomic,copy)NSString *name;

@end

//Rent3.m

#import "Rent3.h"

@implementation Rent3

//并没有提供租住的能力,无法实现声明的协议要求

@end

//结果

2015-11-10 19:18:15.737 RentHouse[7738:124003] 我是Li,我打电话找房源

 

协议1

原文:http://www.cnblogs.com/liuyingjie/p/4954037.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!