// Person.hspa
#import <Foundation/Foundation.h>.net
typedef void(^blockType)();orm
@interface Person : NSObjectget
// 定義一個參數是block的方法it
//- (void)test:(blockType) myblock;io
- (void)test:(void(^)()) myblock;test
- (blockType) test2;import
@end gc
//方法
// Person.m
#import "Person.h"
@implementation Person
- (void)test:(blockType)myblock {
myblock();
}
- (blockType)test2 {
return ^{
NSLog(@"test2");
};
}
//
// main.m
#import <Foundation/Foundation.h>
#import "Person.h"
// block做爲方法的參數,傳遞block參數
//void test(void(^myblock)()){
// // 調用block
// myblock();
//}
// block 做爲方法的返回值
//void (^)() test() { // 報錯
//
//}
typedef void(^blockType)();
blockType test() {
blockType block = ^ {
NSLog(@"test -- block");
};
return block;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
void (^block1)() = ^{
NSLog(@"*******");
NSLog(@"*******");
};
block1();
//test(block1); // 打印出兩行*
blockType t1 = test();
t1(); // test -- block
Person *p = [[Person alloc]init];
// block類型做爲方法的參數使用
[p test:^{
NSLog(@"inblock");
}];
// 返回值是block類型的方法
blockType b1 = [p test2];
b1();
}
return 0;
}