有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 ;
} // 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

推荐深度阅读文章

04-13 01:10