IOS委托机制


先说个简单的例子

  妈妈每天要买菜,洗衣服,做饭和上班。妈妈想让爸爸上班。换成代码是妈妈有四个方法 买菜 洗衣服 做饭 上班四个函数,妈妈委托爸爸去上班,所以爸爸要实现上班的函数。

先创建委托

#import <Foundation/Foundation.h>

@protocol setProtocol <NSObject>
//上班
-(NSString*)shangban;

@end

再创建妈妈这个类

.h文件

#import <Foundation/Foundation.h>

#import "setProtocol.h"
@interface Mother : NSObject
//此属性用于指定爸爸对象,此对象必须实现setProtocol协议。
@property(nonatomic,retain) id<setProtocol> detegate;
//买菜
-(NSString*)maicai;
//洗衣服
-(NSString*)xiyifu;
//做饭
-(NSString*)zuofan;
@end

 .m文件

#import "Mother.h"

@implementation Mother
@synthesize detegate=_detegate;
//买菜
-(NSString*)maicai{
    return @"买菜\n";
}
//洗衣服
-(NSString*)xiyifu{
    return @"洗衣服\n";
}
//做饭
-(NSString*)zuofan{
    return @"做饭\n";
}
-(NSString*)shangban{
    return [_detegate shangban];
    
}
@end

实现爸爸这个类

.h

#import <Foundation/Foundation.h>
#import "setProtocol.h"
@interface father : NSObject<setProtocol>

@end

.m

#import "father.h"

@implementation father
-(NSString*)shangban{
    return @"上班";
}
@end

csdn下载地址:http://download.csdn.net/detail/wenwei19861106/4937042

移动开发qq群:59516399


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM