block使用场景(保存代码段)
1.模型CellItem.h
#import <Foundation/Foundation.h> @interface CellItem : NSObject @property (strong, nonatomic) NSString *title; /** 保存点击cell时要执行的代码*/ @property (strong, nonatomic) void(^block)(); + (instancetype)itemWithTitle:(NSString *)title; @end
2.模型CellItem.m
#import "CellItem.h" @implementation CellItem + (instancetype)itemWithTitle:(NSString *)title { CellItem *item = [[self alloc] init]; item.title = title; return item; } @end
3.TableViewController.m
#import "TableViewController.h" #import "CellItem.h" @interface TableViewController () @property (strong, nonatomic) NSArray *items; @end @implementation TableViewController - (void)viewDidLoad { [super viewDidLoad]; CellItem *item1 = [CellItem itemWithTitle:@"撸代码"]; item1.block = ^{ NSLog(@"撸代码"); }; CellItem *item2 = [CellItem itemWithTitle:@"谈恋爱"]; item2.block = ^{ NSLog(@"谈恋爱"); }; CellItem *item3 = [CellItem itemWithTitle:@"挣大钱"]; item3.block = ^{ NSLog(@"挣大钱"); }; self.items = @[item1,item2,item3]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - Table view data source - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return _items.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *ID = @"cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; if (cell==nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID]; } // if (indexPath.row==0) { // cell.textLabel.text = @"撸代码"; // }else if (indexPath.row==1){ // cell.textLabel.text = @"谈恋爱"; // }else if (indexPath.row==1){ // cell.textLabel.text = @"挣大钱"; // } CellItem *item = self.items[indexPath.row]; cell.textLabel.text = item.title; return cell; } -(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ // if (indexPath.row==0) { // cell.textLabel.text = @"撸代码"; // }else if (indexPath.row==1){ // cell.textLabel.text = @"谈恋爱"; // }else if (indexPath.row==1){ // cell.textLabel.text = @"挣大钱"; // } //使用block,免去繁琐的if - esle判断 CellItem *item = self.items[indexPath.row]; if (item.block) { item.block(); } } @end