iOS委托的基本用法

来源:互联网 发布:mysql not exists 用法 编辑:程序博客网 时间:2024/05/22 20:28

委托就是委托其他类去帮自己做某些事情,委托本身定义一系列的方法,但并不去实现这些方法,这些方法由实现了委托的类去实现,下面的例子就是委托ViewController类去实现testDelegate方法

//  TestBlock.h

#import <Foundation/Foundation.h>@protocol TestBlockDelegate <NSObject>- (void) testDelegate;@end@interface TestBlock : NSObject@property(nonatomic, assign) id<TestBlockDelegate> delegate;@property(nonatomic, copy) void(^callBack)(NSString * name, NSInteger age);- (instancetype)init;- (void) testPrintWithName:(NSString *) name withAge:(NSInteger) age;@end


//  TestBlock.m

#import "TestBlock.h"@implementation TestBlock- (instancetype)init{    self = [super init];    if (self) {        self = [super init];    }    return self;}- (void)testPrintWithName:(NSString *)name withAge:(NSInteger)age{    _callBack(name, age);        if (self.delegate && [self.delegate respondsToSelector:@selector(testDelegate)]) {        [self.delegate testDelegate];    }}@end


测试:

@interface ViewController () <TestBlockDelegate>@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.           TestBlock * tb = [[TestBlock alloc] init];        tb.delegate = self;       [tb setCallBack:^(NSString * name, NSInteger age) {    //    NSLog(@"%@--%li", name, (long)age);    }];        [tb testPrintWithName:@"dz" withAge:11];    }- (void)testDelegate{    NSLog(@"%s", __func__);}

输出:

2015-11-02 15:05:26.367 02-runtime[3160:88382] -[ViewController testDelegate]


0 0