1.block encapsulates a piece of code as a property
Declare the Block property in the model class, and note that the properties of the block are to use copy or there will be a problem
@property (copy, nonatomic) void (^actionblock) ();
@property (copy, nonatomic) void (^actionwithpapameterblock) (int papameter);
@property (copy,nonatomic) NSString * (^ACTIONTORETURNSTIRNG) ();
Other controllers Create model class objects and assign a piece of code to the Block property. Once the block attribute has been added to the cell's model class, it is convenient to call the controller that clicked the cell jump into the block code.
No return value no parameter block
_model = [[Modelalloc]init];
_model.actionblock = ^{
NSLog (@ "Actionblock");
};
No return value with parameter block
_model.actionwithpapameterblock = ^ (int a) {
NSLog (@ "%d", a);
};
has a return value
_MODEL.ACTIONTORETURNSTIRNG = ^{
[Email protected] "Hello";
};
Calling block in other methods
-(Ibaction) TAPBTN: (ID) sender
{
_model.actionblock ();
_model.actionwithpapameterblock (10);
NSLog (@ "%@", _model.actiontoreturnstirng ());
}
2. Controller Transfer value
In the controller that needs to pass the value defines the block, here passes the input of the nsstring in the Uitextfield, and declares the initialization method
Typedefvoid (^textfieldchangedblock) (NSString *text);
-(ID) Initwithblock: (textfieldchangedblock) block;
Use member variables in the implementation file to record block
@implementation model{
Textfieldchangedblock _changedblock;
}
-(ID) Initwithblock: (textfieldchangedblock) block
{
self = [super init];
if (self) {
_changedblock = Block;
}
return self;
}
Execute block
-(void) Click
{//return
_changedblock (Self.textFiled.text);
[Self dismissviewcontrolleranimated:yes completion:nil];
}
Block value, the class where the block is stored in a controller that needs to display TextField content
Detailviewcontroller *detail = [[Detailviewcontroller alloc]initwithblock:^ (NSString *text) {
[Self.label Settext:text];
}];
3. A block was used to load scene footage with a sprite kit
The host controller uses the method provided by the custom scene to load the scene footage
[Scene loadsceneassetswithcompletionhandler:^{
Scene.scalemode =skscenescalemodeaspectfill;
[Skview Presentscene:scene];
}];
Block implementation
Typedefvoid (^assetloadcompletionhandler) (void);
-(void) Loadsceneassetswithcompletionhandler: (Assetloadcompletionhandler) callback
{
Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default,0), ^{
[Selfloadsceneassets];
if (callback) {
Dispatch_async (Dispatch_get_main_queue (), ^{
Callback ();//Callback
});
}
});
}
Defragment the block in iOS as a property, pass value, callback usage