block与GCD--39:用block降低代码分散程度

2023-11-22 08:29:50 浏览数 (2)

  • 代理的实现
代码语言:javascript复制
#import <Foundation/Foundation.h>
@protocol StudentDeleagte<NSObject>
- (void)dosomething:(NSString *)str;
@end
@interface Student : NSObject
@property (nonatomic,weak) id<StudentDeleagte> delegate;
- (void)startDeleagte;
@end
=============
#import "Student.h"
@implementation Student
- (void)startDeleagte{
    if (_delegate && [_delegate respondsToSelector:@selector(dosomething:)]) {
        [_delegate dosomething:@"delegate"];
    }
}
@end
=============
- (void)viewDidLoad {
    [super viewDidLoad];
    Student *stu =  [[Student alloc]init];
    stu.delegate = self;
    [stu startDeleagte];
}
- (void)dosomething:(NSString *)str {
    NSLog(@"%@",str);
}
  • 块的实现
代码语言:javascript复制
#import <Foundation/Foundation.h>
typedef void(^dosomethingBlock)(NSString *str);
@interface Student : NSObject
- (void)startBlock:(dosomethingBlock)block;
@end
=============
#import "Student.h"
@implementation Student
- (void)startBlock:(dosomethingBlock)block{
    if (block) {
       block(@"block");
    }
}
@end
=============
- (void)viewDidLoad {
    [super viewDidLoad];
    Student *stu =  [[Student alloc]init];
    [stu startBlock:^(NSString *str) {
        NSLog(@"%@",str);
    }];
}

由此可见,使用代理和块相比,使用块可以令API变得更加紧致,同时调用起来很方便

0 人点赞