iOS 中Block的使用场景

来源:互联网 发布:个推公司怎么样知乎 编辑:程序博客网 时间:2024/05/20 23:38

block在开发中的使用场景(保存代码)

//定义类型//BlockType:类型别名//typedef void(^BlockType)();//---1111---//说明:2个---111---结合与---222---等价@interface ViewController ()//@property (nonatomic, strong) BlockType block;---1111---//block怎么声明,就怎么定义成属性@property (nonatomic, strong) void(^block)();//---222---@end
#import "KXTableViewController.h"----------///******导入模型类********/#import "CellItem.h"----------// 1.tableView展示3个cell,打电话,发短信,发邮件@interface KXTableViewController()@property (nonatomic, strong) NSArray *items;@end@implementation KXTableViewController- (void)viewDidLoad{    [super viewDidLoad];    CellItem *item0 = [CellItem itemWithTitle:@"打电话"];    item0.block=^{        NSLog(@"000000000");    };    CellItem *item1 = [CellItem itemWithTitle:@"发短信"];    item1.block=^{        NSLog(@"11111111");    };    CellItem *item2 = [CellItem itemWithTitle:@"发邮件"];    item2.block=^{        NSLog(@"2222222");    };    _items = @[item0,item1,item2];}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    return _items.count;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    static NSString *ID = @"menu";    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];    if (!cell) {        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];    }    CellItem *item = self.items[indexPath.row];    cell.textLabel.text = item.title;    return cell;}// 点击cell就会调用- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{    CellItem *item = self.items[indexPath.row];    if (item.block) {        item.block();    }   }@end

自定义#import “CellItem.h”类
.h文件

//  CellItem.h#import <Foundation/Foundation.h>@interface CellItem : NSObject// 设计模型:控件需要展示什么内容,就定义什么属性@property (nonatomic, strong) NSString *title;*//保存每个cell要做的事情*@property (nonatomic, strong)  void(^block)();+ (instancetype)itemWithTitle:(NSString *)title;@end

.m文件

#import "CellItem.h"@implementation CellItem+ (instancetype)itemWithTitle:(NSString *)title{    CellItem *item = [[self alloc] init];    item.title=title;    return item;}@end
0 0