Callbacks are often used in iOS development, and the following describes how to implement callbacks with block.
1 #import <Foundation/Foundation.h>23@interface block:nsobject 4 5 + (void) Getblock: (void (^) (NSString *)) Someblock; 6 7 @end
BLock.h
1 #import "BLock.h"2 #import<Foundation/Foundation.h>3 4 @implementationBLock5 6+ (void) Getblock: (void(^) (NSString *)) Someblock7 {8NSLog (@"we is in a getblock function");9Someblock (@"BLOCK Go Go");Ten } One @end
BLOCK.M
There is a block class with a static method that callbacks a string data via Someblock.
1 #import<Foundation/Foundation.h>2 #import "BLock.h"3 intMainintargcConst Char*argv[])4 {5 6 @autoreleasepool {7 8[BLock getblock:^ (NSString *str) {NSLog (@"%@", str);}];9 }Ten return 0; One}
main.m
The str parameter returned by the callback is displayed in main.
The output is as follows
from £º31.065 myfirstapp[2430:303 in a getblock function-01 :31.066 myfirstapp[2430:3030
You can also rewrite the BLock.h and block.m files as follows:
1 #import <Foundation/Foundation.h>23 typedef void (^ablock) (NSString *); // define a block as a new type 4 5 @interface Block:nsobject 6 7 + (void) Getblock: (Ablock) Someblock; 8 9 @end
BLock.h
1 #import "BLock.h"2 #import<Foundation/Foundation.h>3 4 5 @implementationBLock6 7+ (void) Getblock: (ablock) Someblock8 {9NSLog (@"we is in a getblock function");TenSomeblock (@"BLOCK Go Go"); One } A @end
BLOCK.M