iOS Block、Delegate使用场景

529 阅读1分钟

Block

  • 临时性的,只会调用一次的
  • 回调函数较少,比如只需要:完成状态、是否报错、加载进度 ######优点:
  1. 代码简洁,使用简单 ######缺点:
  2. 使用不当容易造成循环引用
  3. 对局部变量进行写操作时,需要添加__block
// AFNetworking 示例
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
              uploadTaskWithStreamedRequest:request
              progress:^(NSProgress * _Nonnull uploadProgress) {
                  // This is not called back on the main queue.
                  // You are responsible for dispatching to the main queue 
                  });
              }
              completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                  if (error) {
                      NSLog(@"Error: %@", error);
                  } else {
                      NSLog(@"%@ %@", response, responseObject);
                  }
              }];
// MJRefresh 示例
self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
    //Call this Block When enter the refresh status automatically
}];
// UIView 动画示例
[UIView animateWithDuration:2
                      delay:2
     usingSpringWithDamping:.5
      initialSpringVelocity:.5
                    options:UIViewAnimationOptionRepeat
                animations:^{
   
} completion:^(BOOL finished) {   

}];

Delegate

  • 回调函数较多,并且会多次调用
  • 存在一定的顺序 ######优点:
  1. 减少代码耦合性
  2. 流程、逻辑较为清晰,维护成本相对较低 ######缺点:
  3. 因为声明和实现是分开的,可能在代码阅读需要来回切换查找,相对麻烦点
// UITextField 示例
@protocol UITextFieldDelegate <NSObject>
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;        // return NO to disallow editing.
- (void)textFieldDidBeginEditing:(UITextField *)textField;           // became first responder
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField;          // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
- (void)textFieldDidEndEditing:(UITextField *)textField;   
// UITableView 示例
@protocol UITableViewDelegate<NSObject, UIScrollViewDelegate>
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;   // custom view for header. will be adjusted to default or specified header height
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;   // custom view for footer. will be adjusted to default or specified footer height