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
- iOS委托的基本用法
- 委托的基本用法
- C#委托的基本用法
- 委托Delegate的基本用法
- 委托的基本用法(回顾)
- C#委托基本用法
- 代理(委托)delegate基本用法
- iOS UILabel的基本用法
- iOS CoreData的基本用法
- ios NSNotFound的基本用法
- ios NSTimer的基本用法
- iOS分类的基本用法
- iOS 通知的基本用法
- iOS 通知的基本用法
- iOS UIWebView的基本用法
- iOS--NSAttributedString的基本用法
- iOS NSScanner的基本用法
- IOS的GCD基本用法
- HTML5怎么设置滚动字幕?
- AbstractCollection 抽象类 源代码
- 关于EL标签中 no empty 疑惑加入判断一个list是否为空时 用 ${not empty list}个 ${... ne null} 有什么区别了 关于EL标签中 no empty 疑惑
- prop和attr的区别与用法
- C语言求最大公约数问题
- iOS委托的基本用法
- appstore审核指南
- 深入分析Java线程中断机制
- 多线程,主线程与子线程的通信Handler Message sendmessage与handlemessage obtainmessage
- Dubbo 本地安装
- jQuery ajax请求
- Redis能干啥?细看11种Web应用场景
- 聊一聊人生,关于陷阱、生活和爱
- 原生JS实现addClass,removeClass,toggleClass ,附:类似jquery hover事件