[ios] delegate用法

认为delegate 也是nsnotication一样的一种消息发送机制.

1.定义delegate

testA类的h文件

@protocol testDelegate;

1.@interface  testA:NSObject

@property(assign) id<testDelegate> mydelegate;

 @end

@protocel testDelegate<NSObject>

//要让别的类实现的方法

-(void) testDelegateFunc;

@end

调用delegate方法

testa.m文件

@implementation testA

@synthesize mydelegate;

//在某个地方你想调用的时候调用

if ([self.mydelegate respondsToSelector:@selector(testDelegateFunc)]) {
        [self.mydelegate testDelegateFunc];
    }

@end

下一步你让谁实现这个方法,你就让谁实现这个接口(delegate)

我让testb类实现接口

testb.h

#import "testa.h"

@interface testb:NSobject<testDelegate>

@end

testb.m文件 实现这个方法就行

viewdidload{

testa * a=[teata alloc]init];

a.mydelegate=self;

}

-(void) testDelegateFunc{

NSLog("%@",@"这是testa的方法,testb实现testa的方法,这就是delegate模式");

}

原文地址:https://www.cnblogs.com/jinjiantong/p/2961134.html