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