Block bloggers use blocks in three simple ways:
- Defined and used like a function, unlike a function, which can be defined inside or outside a method
- Property defined as a property
- Used as a modifier.
The next thing to show; 1. Define and use functions like functions, unlike functions that can be defined inside or outside a method
1) Used in methods
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSString *(^thisBlock) (NSString *thisName) = ^(NSString *name){ return [NSString stringWithFormat:@"%@:%@",@"name",name]; }; NSLog(@"%@",thisBlock(@"xiaoming")); }Copy the code
2) Use it outside of a method, as if defining a method
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
BlockVoid(24);
}
void (^BlockVoid) (int age) = ^(int xiaomingAge){
NSLog(@"xiaomingAge:%d",xiaomingAge);
};
Copy the code
A block can be defined inside a method as well as outside a method. If a block is defined outside a method, it looks like a function.
2. This is an approach we often use, for example
/ / @property(nonatomic,copy)void (^myBlock) (NSString *name,int age); / / @property(nonatomic,copy)void (^myBlock) (NSString *name,int age); / / @property(nonatomic,copy)NSString *(^haveReturnBlock) (NSString *name); / / @property(nonatomic,copy)NSString *(^haveReturnBlock) (NSString *name); // use - (void)test2 {_myBlock(@"CodeLiu",24); } - (NSString *)test3 {return _haveReturnBlock(@" little "); }Copy the code
Here’s another interesting way to use it:
#import <Foundation/ foundation.h > /** Define a block @param returnContent return value */ typedef void(^RetureContentBlock)(id) returnContent); @interface LHBlockForUse: NSObject /** Declare a variable with a defined block */ @property(nonatomic,copy)RetureContentBlock returnBlock; - (void)test1 {_returnBlock(@"You can put every type in here"); }Copy the code
3. Used as a modifier
Variables outside the Block cannot be modified inside the Block. To do so, they need to be modified with __block
__block int lastAge = 24;
void (^lastAgeBlock) (int age) = ^(int addAge){
lastAge = lastAge + addAge;
NSLog(@"xiaomingLastAge:%d",lastAge);
};
lastAgeBlock(1);
Copy the code
The above is the simple application of Block, if where write bad welcome to correct, download address: simple use of Block