The essence of block syntax is: function pointer
Block syntax callback is implemented by passing function pointers.
The Paster code is fast:
Main function:
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 class:
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) ahyperlink :( nsstring *) string {nslog (@" % @ ", string) ;}- (void) method {toolclass * tool = [[toolclass alloc] init]; [Tool handledata: 0 numberb: 0 function: ^ (int A, int B) {nslog (@ "% 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 // Block Value passing parameter, no return value-(void) handledata :( INT) A numberb :( INT) B function :( void (^) (int, int B) testfunction {int AAA = 5, BBB = 10; testfunction (AAA, BBB);} // The block can not only pass parameters, but also return values-(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 ;}; // int (^ completion) (INT) = ^ (INT A1) {// return A1 + 5; //}; int (^ myblock) (INT) = ^ (INT A1) {return A1 ;}; @ end