Cat Share, must boutique
Original articles, welcome reprint. Reprint Please specify: Sanayu's Blog
Address: http://blog.csdn.net/u013357243
One: Scene
We have an object, he has two methods, one is learning study, the other is running run,
This person has a quirk, must learn after running, in order to achieve this method and can be invoked conveniently, we let running and learning to return to their own this object as a shortcut to the next call, the code is as follows:
Call:
int main(intconstchar * argv[]){ @autoreleasepool { //初始化人 Person *p = [[Person alloc] init]; //调用 [[p study] run]; return0;}
Person object:
//Person.h #import <FOUNDATION/FOUNDATION.H> @interface person : nsobject -(person *) study;-(person *) run; @end
// Person.m#import "Person.h"@implementation Person- (Person *)study{ NSLog(@"study----"); returnself;}- (Person *)run{ NSLog(@"run----"); returnself;}@end
Run results
Two: Block chain-type structure implementation
Call:
int main(intconstchar * argv[]){ @autoreleasepool { Person *p = [[Person alloc] init]; p.study(@"xx宝典").run().study(@"xx剪发"); } return0;}
Person object:
//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); returnself; };}- (Person *(^)())run{ return ^{ NSLog(@"run----"); returnself; };}@end
In this area, we
P.study (@ "xx treasure book"). Run (). Study (@ "XX hair cut");
Call study method: P.study
Execute Block:p.study (@ "xx Treasure book")
Combining the method of person's internal writing
- (Person *(^)(NSString *))study{ return ^(NSString *name){ NSLog(@"study----%@", name); returnself; };}
Obviously, when executing p.study (@ "xx treasure"), the inside is a return value is the block of the person* type (the last return self), which explains why the next sentence can continue to be invoked with a point. This means that a block is returned, and there is a return value in the block, and the return value is the object self of the person.
The parameters here are a bit dizzy, remember, with the clever use of a chain-structured block, simply understand it.
Execution results
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Cat learns the magic of the block of iOS using block for chained programming