1. Traditional programming
Method of person
-(void) Eat
{
NSLog (@ "eat");
}
-(void) Learn
{
NSLog (@ "learning");
}
-(void) play
{
NSLog (@ "Entertainment");
}
Do things continuously
Person *p = [[Person alloc] init];
[P eat];
[P learn];
[P play];
2. Chain programming without block
Method of person
-(person *) eat
{
NSLog (@ "eat");
return self;
}
-(person *) Learn
{
NSLog (@ "learning");
return self;
}
-(person *) play
{
NSLog (@ "Entertainment");
return self;
}
To do things in succession, so that they look dizzy
Person *p = [[Person alloc] init];
[[[P eat] learn] play];
3. Chained programming with block
Method of person
-(Person * (^) ()) Eat
{
Return ^{
NSLog (@ "eat");
return self;
};
}
-(Person * (^) ()) Learn
{
Return ^{
NSLog (@ "learning");
return self;
};
}
-(Person * (^) ()) Play
{
Return ^{
NSLog (@ "Entertainment");
return self;
};
}
Do things continuously
Person *p = [[Person alloc] init];
P.eat (). Learn (). Play ();
4. Chained programming with parameters
For example, the way people eat, the parameters are NSString *food
-(Person * (^) ()) Eat: (nsstring*) Food
{
return ^ (food) {
NSLog (@ "eat");
return self;
};
}
If this is the above: P.eat can not be followed: food, because p.eat itself is equivalent to [P EAT: (NSString *) food], if write p.eat:food, equivalent to [P Eat::food], this is wrong.
So the correct wording:
-(Person * (^) (nsstring* food)) eat
{
return ^ (nsstring* food) {
NSLog (@ "eat----%@", food);
return self;
};
}
Do things continuously
P.eat (@ "cabbage"). Learn (). Play ();
5. In summary, the use of block to achieve chain programming is nothing more than: The return value of the method is a block,block inside the actual implementation of the method, block internal return to self; If there are parameters, pass through the parameters of the block.
-(The return value is block) method name
{
Return *{
The block is loaded with code that's really going to execute.
return self;
};
}
IOS uses block for chained programming