您的位置:首页 > 移动开发 > IOS开发

关于iOS开发中的delegate

2015-12-10 00:02 519 查看
有A、B两个对象,A要完成某件事,想让B帮它做。

这时候,A中就要实例化一个B的对象b,A还要在头文件中声明协议,然后在B中实现协议中对应的方法。

这时候再把A的delegate设置为b,在需要的地方,就可以调用B来完成任务了。

//  main.m
#import <Foundation/Foundation.h>
#import "A.h"
#import "B.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
A *a = [[A alloc] init];
B *b = [[B alloc] init];
a.delegate = b;
[a doSomething];
}
return 0;
}

//  A.h
#import <Foundation/Foundation.h>
#import "CertainDelegate.h"

@interface A : NSObject
@property (weak,nonatomic) id<CertainDelegate> delegate;
- (void)doSomething;
@end

//  A.m
#import "A.h"
#import "B.h"

@interface A ()
@end

@implementation A
- (void)doSomething{
[_delegate requiredFunc];
}

@end

//  B.h
#import <Foundation/Foundation.h>
#import "CertainDelegate.h"

@interface B : NSObject<CertainDelegate>
@end

//  B.m
#import "B.h"

@interface B ()
@end

@implementation B
-(void)requiredFunc{
NSLog(@"requiredFunc is running.");
}
@end

//  CertainDelegate.h
#import <Foundation/Foundation.h>

@protocol CertainDelegate <NSObject>
- (void)requiredFunc;
@end


推荐深度阅读文章
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: