The use of BLOCK in iOS _ using block to implement chain Programming
I. Scenario
We have an object. He has two methods: Learning study and running,
This person has a quirk and must learn it after running the step. In order to realize this method and make it easy to call, we allow both the running and learning to return our own object as a shortcut for the next call, the Code is as follows:
Call:
Int main (int argc, const char * argv []) {@ autoreleasepool {// initialized by Person * p = [[Person alloc] init]; // call [[p study] run]; return 0 ;}
Target persons:
// Person.h#import
@interface Person : NSObject- (Person *)study;- (Person *)run;@end
// Person.m#import Person.h@implementation Person- (Person *)study{ NSLog(@study----); return self;}- (Person *)run{ NSLog(@run----); return self;}@end
Running result
II. Implementation of block chain structure
Call:
Int main (int argc, const char * argv []) {@ autoreleasepool {Person * p = [[Person alloc] init]; p. study (@ xx baodian ). run (). study (@ xx haircut);} return 0 ;}
Target persons:
//Person.h@interface Person : NSObject- (Person *(^)(NSString *name))study;- (Person *(^)())run;@end
//Person.m@implementation Person- (Person *(^)(NSString *))study{ return ^(NSString *name){ NSLog(@study----%@, name); return self; };}- (Person *(^)())run{ return ^{ NSLog(@run----); return self; };}@end
Here, we
P. study (@ "xx "). run (). study (@ "xx Haircut ");
Call the study method: p. study
Execute block: p. study (@ "xx ")
Combined with the internal Writing Method of person
- (Person *(^)(NSString *))study{ return ^(NSString *name){ NSLog(@study----%@, name); return self; };}
Obviously, when p. when study (@ "xx "), the internal return value is a person * type (the final return self) block, which explains why the next sentence can be called with points. That is to say, a block is returned, and the returned value is the self object of person.
The parameters here are a bit dizzy. Remember, the clever usage of block with chained structure is good for a simple understanding.
Execution result