塊文法的本質是:函數指標
塊文法的回調是通過傳遞函數指標實現的。
貼圖貼碼為快:
主函數:
View Code
#import <Foundation/Foundation.h>#import "HomeClass.h"int main(int argc, const char * argv[]){ @autoreleasepool { HomeClass *home = [[HomeClass alloc] init]; [home method]; } return 0;}
HomeClass類:
View Code
#import <Foundation/Foundation.h>@interface HomeClass : NSObject- (void)method;- (void)aactin:(NSString *)string;@end
View Code
//// HomeClass.m// BlockDemo//// Created by hanjun on 13-3-14.// Copyright (c) 2013年 CompanyOfHanJun. All rights reserved.//#import "HomeClass.h"#import "ToolClass.h"@implementation HomeClass- (void)aactin:(NSString *)string{ NSLog(@"%@",string);}- (void)method{ ToolClass *tool = [[ToolClass alloc] init]; [tool handleData:0 numberb:0 Function:^(int a, int b) { NSLog(@"%d %d",a,b); }]; [tool action:^NSString *(NSString * string) { NSLog(@"callBack:%@",string); return @"hanjun"; }]; }@end
ToolClass類
View Code
#import <Foundation/Foundation.h>@interface ToolClass : NSObject-(void)handleData:(int)a numberb:(int)b Function:(void (^)(int a,int b))testFunction;- (void)presentViewCompletion:(void (^)(void))completion;- (void)action:(NSString *(^)(NSString *))string;- (void)aactin:(NSString *)string;@end
View Code
//// ToolClass.m// BlockDemo//// Created by hanjun on 13-3-14.// Copyright (c) 2013年 CompanyOfHanJun. All rights reserved.//#import "ToolClass.h"@implementation ToolClass//塊值傳參,沒有傳回值-(void)handleData:(int)a numberb:(int)b Function:(void (^)(int a,int b))testFunction{ int aaa=5,bbb=10; testFunction(aaa,bbb);}//塊不僅可以傳參,還可以有傳回值- (void)action:(NSString *(^)(NSString *))string{ NSString * backReturn = string(@"yhy"); NSLog(@"backReturn = %@",backReturn);}int (^oneFrom)(int) = ^(int anInt){ return anInt-1;};int (^completion)(int)=^(int a){ return a;};//int (^completion)(int)=^(int a1){// return a1+5;//};int (^myBlock)(int)=^(int a1){ return a1;};@end