- 代理的实现
#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);
}
- 块的实现
#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变得更加紧致,同时调用起来很方便