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

posted on 2012-12-28 11:20  南瓜饼  阅读(1627)  评论(5编辑  收藏  举报

导航