Method Chaining in Objective-C and make your own Chaining Methods to create a calculator

Needone App
2 min readMay 9, 2017

--

When I was using the Masonry, I was shocked by author’s thoughts on bring Functional Programming to objective-c, which present a clean and concise way on developing. Normally a chain method looks like:

Method Chaining is simple but powerful, which has three key points, everyone can create his/her own chaining method after knowing this:

To be able to create chain methods in objc, there are some features:

  1. Methods can be called consecutively;
  2. Each of the method return the same type, in this case is class instance;
  3. Special in Objective-C, as which only allows to use square brackets to call methods. parenthesis is used for block.

Hold those ideas in mind, it is quite nature to think about creating a new class for the Chaining Methods Calculator:

So you can call the calculator methods like:

CalculateChain *calc = [[CalculateChain alloc] init];
calc.add(10).minus(5).multiply(100).divide(2);
NSLog(@"results: %f", calc.result);

Be aware about the method:

-(CalculateChain*(^)(float))minus{
return ^CalculateChain *(float value){
_result -= value;
return self;
};
}

Which is a getter for property minus, it takes a

Some Improvements:

The above class is enough to use, however it still has some drawbacks:

  1. Every time to use, we have to create a new class/class instance
  2. A global variable is created to store the final results.

Luckily, objective-c provide a extension and category which can help developers to add more functions to existing classes. In our case, all the NSNumber object can have the chaining methods.

If you have any thoughts, please leave a comment.

Reference:

Demo Project on Github: Method-Chaining-in-Objective-C

--

--

No responses yet