块语法的本质是:函数指针
块语法的回调是通过传递函数指针实现的。
贴图贴码为快:
主函数:
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