A project with two ways showing how to create chain methods in objective-c
This project illustrates how to create chaining methods in Objective-C. When I used the Masonry, I was shocked by author's thoughts on bring Functional Programming
to objective-c, which present clean and concise code to all developers. Method Chaining is simple but powerful, which has three key points, everyone can create his/her own chaining method after knowing this:
- Methods can be called consecutively.
- Each of the metod return the same type
- Special in Objective-C, as which only allows to use sqaure brackets to call methods. parathesis is used for block.
Thanks Kangzubin's tutorial and idea, method 1 is common method that many developer can come up with.
CalculateChain *calc = [[CalculateChain alloc] init];
calc.add(10).minus(5).multiply(100).divide(2);
NSLog(@"results: %f", calc.result);
Method 1 is similar to the one used in Masonry
. However, an instance must be created every time you call those chaining methods. So why not use categroy
(If you don't know how, go have a check at Swift Extension and Objective-C category).
With categroy
in hand, all the NSNumber
type value can call those chaining methods straight away.
NSNumber *num = @0.0;
NSLog(@"results: %@", num.add(10).minus(5).multiply(100).divide(2));
- Method Chaining in Swift