block instead of delegate, use block as much as possible, and consider using protocol for a large number of delegate methods.
1.Block syntax summary and examples are as follows:
1. Block mode of common code blocks
ReturnType (^blockname) (parametertypes) = ^returntype (parameters) {
Block code
};
Use no example:
Int (^ABC) (int a) = ^int (int a) {
return a+1;
};
int AA = ABC (2);
NSLog (@ "%d", AA);
2. Attribute Mode block
@property (nonatomic, copy) ReturnType (^blockname) (parametertypes);
Examples of Use:
1. Defining attributes
@property (nonatomic,copy) int (^testblock) (NSString *);
2. Setting Usage Properties
[Self Settestblock:^int (nsstring *a) {
return 0;
}];
3. Method Parameters Block
-(void) Somemethodthattakesablock: (ReturnType (^) (parametertypes)) Blockname {
Block code
};
Using Example 1:
1. Non-parametric definition and implementation:
-(void) Testblockfun: (void (^) ()) completion{
NSLog (@ "execute");
if (completion) {
Completion ();
}
}
2. Parameter-Free block invocation:
[Self testblockfun:^{
NSLog (@ "callback End");
}];
Using Example 2:
1. With parameter definition and implementation:
-(void) Testblockfun: (int (^) (int a,int b)) complate{
if (complate) {
int c = complate (3,5);
NSLog (@ "c:%d", c);
}
}
2. Block call with parameter type:
[Self testblockfun:^int (int a, int b) {
return a+b;
}];
4. As a parameter
[Someobject Somemethodthattakesablock: ^returntype (Parameters) {
Block code
}];
Examples of Use:
1. Definition and implementation
-(void) Testblockfun: (void (^) (NSString *)) complate{
if (complate) {
Complate (@ "Success");
}
}
2. Call
[Self testblockfun:^ (nsstring *str) {
NSLog (@ "str:%@", str);
}];
5. Using typedef definitions
typedef returntype (^typename) (parametertypes);
TypeName blockname = ^ (parameters) {
};
Examples of Use:
typedef void (^blocktestname) (NSString *);
Call:
[Self setname:^ (nsstring *a) {
}];
2.Block Modified value: Use __block to modify the value of an external variable inside the block.
__block int someincrementer = 0;
[Someobject somemethodthattakesablock:^{
someincrementer++;
}];
3.Block Loop reference, block will hold object, block object also has block, will cause block's circular reference, workaround:
__weak typeof (self) weakself = self;//@weakify (self);
[Self somemethodthattakesablock:^{
[Weakself Action];
}];
Block instead of delegate, use block as much as possible, and consider using protocol for a large number of delegate methods.