Sunday, March 30, 2014

Passing CGFloat to methods resets the value of arguments to 0

Recently, I was faced a very weird issue with methods that have CGFloat as argument.

The Problem

We were using cocos2d for our iOS project.  The code was very simple, I was trying to invoke a method of class that takes two CGFloat arguments.

No matter what values I pass to doSomething it always receives 0 or some other garbage value.  Just to be extra sure, I even logged the values of the parameters passed before actually invoking the method.  The values got printed correctly, but the doSomething method always printed 0.

The Explanation

Well, I was stumped here.  This was like the simplest possible code.  Set the value of a variable, pass it to another method and BOOM the value gets reset!

Obviously, this was nothing to do with how I have written the code, others out there must be facing the same issue.  A bit of googling calmed my nerves.

CGFloat is just a typedef wrapper around either a float or a double. Whether it actually is a float or a double depends on the header where CGFloat is defined that your code compiled against.  The CGFloat definition looks something like this

Notice how CGFloat either becomes a float or a double, depending on whether the architecture is 64 bit or not.

All goes well, until you mix code compiled with this flag on, with other code compiled with this flag off (Such as including a binary library with other code). Effectively mixing 64 bit compiled code with 32 bit compiled code.

This can potentially lead to a case where we are passing doubles to methods that are expecting a float.  Since this is all happening at the byte level, no error is thrown and the bytes are just truncated, taking off all of the bits that actually described your value and leaving bits with nothing in them i.e. 0.

In my case, it was happening because I was trying to build a binary for both the Simulator and iPad Air Device.

The Solution

A clean and build should have solved the issue, but I decided to change the method arguments to float instead of CGFloat.  Once I did this change, everything worked as expected!
Thats all folks!  Until we meet again, enjoy your time.

Sunday, February 23, 2014

How to play game voices sequentially when background music is running on iOS

I was recently hacking my way through an open-source iOS game and I was faced with two interesting problem.
  • There are multiple voices and background music that are played at different times.  It was becoming extremely difficult to hear the voices clearly when the background music was turned on.
  • To add to that, there are certain voices that needed to be played in sequence.  For example, when user reaches "Level" "n", we want to play a voice "Level" and then the level number where the user has reached.  For example, if the user has reached Level 3, we want to play "Level" and then "3" since we do not have a distinct voice for every level (may be that's not even scalable).
In this post, we will see how we fixed both this issues using a small wrapper class.

How Do They Do it?

What I ended up doing was to create a small wrapper class that had following main responsibilities:
  • Fades-out the background music to slower volume whenever a voice is playing
  • Fades-in the background music to original volume when voices have finished playing
  • Manage a queue or a playlist of voices which are played in sequence.
We made use of the CDAudioManager class its delegates to implement this class.  Once we had this class in place, it made task really simple.  The code was well encapsulated and we could use it throughout the system consistently.

Without wasting any more time, let's have a look at how actually its done!

Create the Singleton AudioManager

This class needs to act as a service to the application, hence we are going to make it a singleton class.
Initialize Fields
  • Next step is to initializes the CDAudioManager 
  • Build NSMutableArray that will hold the queue of voices for us.  
  • We will also be registering AudioManager as a delegate to the CDAudioManager class.  Hence, we will implement the protocol CDLongAudioSourceDelegate
Enqueue Voices
  • This is where we build the queue of our voices.  
  • If the audioSource is not busy playing any other voice, then we simply play the voice.  When we play the voice we will also make sure that we fade-out the background music to a lower volume.
  • Else we will add the voice to the queue of voices
Implement the Delegate
  • This is where it all comes together.
  • We implement the protocol CDLongAudioSourceDelegate, this protocol has two optional methods
    • cdAudioSourceDidFinishPlaying
    • cdAudioSourceFileDidChange
  • We are only interested in implementing the cdAudioSourceDidFinishPlaying method.  This method will be called every time CDAudioManager finishes playing a voice.
  • Every time this method is called, we know that CDAudioManager has finished playing a voice we can now play the next voice from the queue.
  • If the queue is empty, then we simply fade-in the background music to its original volume.
That's about all that we need to do!  We have successfully setup the AudioManager for voices in our game.  It will nicely play voices one after the other and fade-out the background music when the voice is playing.

For sake of completion and easy understanding, here is the full code for the class

Monday, January 27, 2014

How To Convert Objective C data modles into JSON

Recently, I have been trying my hands at iOS and so far its going good.  I must say, I am still learning things.  Before going further this is a disclaimer from my side, I am by no means an expert on iOS and related technologies, so please consider the views mentioned in this post as strictly my own immature views only.

That said, I was looking for some in-built library/API to convert my Objective C data model classes into JSON without me providing the mapping (or should I say, remapping) of any sort .

Pretty straightforward requirement, I would think.  Partly because of my poor searching skills and partly because of my poor iOS skills, I was kind of surprised to find out that, there are bunch of libraries to convert to and from JSON, however they all needed some sort of mapping to be provided along with the Objective C class to get the job done.

After searching a bit more and looking around, I came across a neat little JSON library that did exactly what I wanted.  The library is called JSONModel.

Here is the description from their site
JSONModel automatically introspects your model classes and the structure of your JSON input and reduces drastically the amount of code you have to write.
The documentation of JSONModel is quite comprehensive and pretty self explanatory, the intent of this post is to keep reminding myself and other fellow developers of using it every time the need arises to convert Objective C classes to JSON.

Ok so enough chatter.  Let's get to business and see an example.

How Do They Do It?


If you are using  Cocoa Pods in your project then installation is as simple as adding the following line to the Podfile.
If you are not using Cocoa Pods in your project then, start using it :)

Basic Usage
  • Let's say we have a Student Objective C class that needs to be converted to and from JSON representation.  
  • All that needs to be done is, extending it from JSONModel class
  • JSONModel is really where the magic happens.  
  • It adds methods like toJSONString and initWithString to convert Objective C class to and from JSON.
  • We need to only declare the properties in the Student class that will be serialized to JSON.
  • The sample code to convert Object C data model to and from JSON would look as follows.
The Student.h file looks like: The Student.m file looks pretty simple The code to convert Student instance to JSON is as follows. The above code has an output that looks like The code to convert JSON string to Student instance is as follows. As you can see we didn't write any extra mapping code to convert Object C data model into JSON. This post is just scratching the surface, JSONModel has got a lot of great features that make this library fun to use.

That's all folks! Hopefully by the next time when we meet, I would be a better iOS developer than what I am today :).

Sunday, December 15, 2013

Win Free Copies of Instant Mock Testing with PowerMock

Here's some good news, I have teamed up with Packt Publishing and we are organizing a Giveaway for you to celebrate the release of my book and two lucky winners stand a chance to win an e-copy of Instant Mock Testing with PowerMock.

What will you get out of this book:

The Cover Page for Mock Testing With PowerMock
  • Understand how to unit test code using PowerMock, through hands-on-examples
  • Learn how to avoid unwanted behavior of code using PowerMock for testing
  • Explore the features of PowerMock through the selection of clear, practical, step-by-step recipes 
Read more about this book and download free Sample Chapter:

How to Enter the contest?

All you need to do is head on over to the and look through the product description of this book and drop a line via the comments below to let us know what interests you the most about this book.
It’s that simple

Dead Line:
Like all good things, this offer does not last for ever.  The contest will close on 31/ 12/ 2013. Winners will be contacted by email, so be sure to use your real email address when you comment.

Till we meet again, Merry Christmas and a Very Happy New Year!

Saturday, November 30, 2013

How to split ember handlebar templates into multiple files using node and grunt

Recently, I was working on a project which used EmberJs.  At the time of writing this post, EmberJs does not provide a way to split the Handlebar templates into multiple files.

This is OK to being with, but soon enough for a decently complex application, keeping all Views in one template files is just not maintainable.  Soon, I was hunting for a way to split the handlebar templates into multiple files to better maintain and manage them.

My search let me to various blogs and a lot of scattered information.  Eventually I was able to find a decent solution for my problem.  In this post, I am going to demonstrate how exactly to solve this problem, in the hope that someone else would benefit from my findings.

How do they do it!

To split the handlebar templates into multiple files, I took help of nodejs and an awesome node module called Grunt.  Here are the steps I followed to get the job done.


  • I am going to assume that you already have npm and nodejs installed on your machine.  If you don't then, please follow the steps mentioned in this link to get them. 
  • Next step, is to get the package.json file which can be used by nodejs.
  • To create a package.json file use the following command.  It will ask some basic questions - please answer them. 

  • This should create a default package.json file which can be used as a foundation for what we want to achieve
  • Next thing we need to do is install a nodejs module called grunt.  This is an awesome task runner which has hundreds of plugins that help us perform  repetitive tasks like minification, compilation, unit testing, linting, etc.
  • The Grunt ecosystem is huge and it's growing every day.  You can use Grunt to automate just about anything with a minimum of effort.
  • To make Grunt work for us, we need to install grunt, grunt-cli, grunt-ember-templates and grunt-contrib-watch node modules.  Install them using the following command.    

  • The grunt-ember-templates module will be used to pre-compile the handlebar templates.
  • The output of this plugin would be a templates.js file which will hold all pre-complied templates.  This can then be easily included in the EmberJs application.
  • The grunt-contrib-watch module exposes a task called watch.  This task can keep an eye on the file system for any changes and invoke the grunt-ember-templates task to recompile the handlebar templates and regenerate the templates.js.  Don't worry if you don't get it at this point.  But trust me, its extremely convenient to have the watch task especially during development.
  • These are all the modules we will need to get the job done.
Creating the Gruntfile.js
  • For Grunt to do its job, it needs to know about the job at hand.
  • We need to inform Grunt about what is to be done, we do this using a file called Gruntfile.js
  • The contents of Gruntfile.js would look as follows

  • This file basically sets up two tasks called emberTemplates and watch.
  • emberTemplates - tasks compiles all handlebar templates (*.hbs files) stored under templates/ directory (and all its sub-directories) and generates a file called templates.js inside the build directory.
  • As explained earlier watch task keeps an eye on the file system modifications to any of the handlebar templates (*.hbs) files.  If these files have been modified then it invokes the emberTemplates task to recompile the handlebar templates and regenerate the templates.js file.
  • The default task for this Gruntfile.js is emberTemplates
  • Let's say we have two template files, index.hbs and login.hbs, their contents are as follows

Light's, Camera, Action!
  • All that is left to do is invoking the grunt command from the command line.

  • This will compile the handlebar templates and generate the templates.js file.  
  • All the handlebar templates are already registered with EmberJs and are ready to be included in an EmberJs application.  
  • The name by which they are registered with EmberJs is same as the name of the file that holds the template.

  • When we doing the development we keep editing the handlebar templates quite often.
  • After we edit them we have to run grunt command again to regenerate the templates.js file.  But as promised earlier we will let watch task do it for us.
  • Run the following command on the command line.

  • This command will never return, it will keep an eye on any changes to the hbs files.
  • Let's update the login.hbs template as follows

  • Since the watch task is already running, it detects the change in the login.hbs and regenerates the templates.js.
  • The idea is to keep that command prompt always running and continue editing the handlebar templates, the templates.js will be seamlessly generated and kept updated for us!
  • Updated templates.js looks as follows.

Isn't this awesome!  We got our modularity and the ease of development, its like have your cake and eat it too!

Well that's all folks, until we meet again, have fun! 

Thursday, October 31, 2013

An Author Is Born - Instant Mock Testing with PowerMock

After quite a few long nights and working weekends, finally the book written by me on PowerMock is published and is available to be bought here, here and here.  It’s available in Paperback and almost all major eBook format.

It’s a book for anyone who wants to learn/master mock testing with PowerMock using the Mockito API.  If you are keen on learning a mocking framework that can mock almost any class, PowerMock is the way to go.  Starting with a basic example of how to create a mock and verify a method invocation, Instant Mock Testing with PowerMock demonstrates various features of PowerMock using clear, practical, step-by-step recipes. 

Moving on from the basics, you will learn how to write unit tests for static, final, and private methods, and write flexible unit tests using argument matchers. Following on from this, you will also learn how to invoke real implementation of some methods and mock only a few methods of a class, using partial mocks or spies. This book will teach you all tricks of the trade and enable you to write good unit tests for a wide range of scenarios.

The Back and Front Cover of the Book
Any feedback would be greatly appreciated (if you want to buy it, please let me know, I can get some deep – pun intended :) – discounts using the Author discount code).

I would like to thank Jayway and the Java Community for a great mocking framework.
I cannot imagine finishing this book without the dedication and support of my loving family, who put up with long nights and working weekends for far longer than I had initially planned for.  

Lastly, I would also want to thank PACKT Publishing and their entire team, without whose efforts this book would have been impossible.  It would be inappropriate on my part, if I didn't extend my special thanks to Govindan, Sherin and Aparna from PACKT Publishing.
I would conclude this post with the preface of the book for your reference:

PowerMock is an open source mocking library for the Java world. It extends the existing mocking frameworks such as EasyMocks (see and Mockito (see to add even more powerful features to them.
PowerMock was founded by Jayway (see and is hosted on Google Code (see
It has a vibrant community with a lot of contributors. Conscious efforts have been made to ensure that PowerMock does not reinvent the wheel. It only extends existing mocking frameworks and adds features that are missing from them. The end result is a mocking library that is powerful and is a pleasure to use.
Sometimes a good design might have to be tweaked to enable testability. For example, use of final classes or methods should be avoided, private methods might need to open up a bit by making them package visible or protected, and use of static methods should be avoided at all costs. Sometimes these decisions might be valid, but if they are taken only because of limitations in existing mocking frameworks, they are incorrect. PowerMock tries to solve this problem. It enables us to write unit tests for almost any situation.
What this book covers
Saying Hello World! (Simple) explains a basic mocking example using PowerMock. It will help us get familiarized with basic mocking and verification syntax.
Getting and installing PowerMock (Simple) demonstrates the steps for setting up PowerMock using IntelliJ IDEA and Eclipse. It also briefly describes other ways of setting up the PowerMock environment.
Mocking static methods (Simple) shows how effortlessly we can mock static methods with PowerMock. Most of the mocking frameworks have trouble mocking static methods. But for Power Mock, it’s just another day at work.
Verifying method invocation (Simple) explains various ways in which we can verify a certain method invocation. Verification is an indispensable part of unit testing.  
Mocking final classes or methods (Simple) covers how easily we can mock final classes or methods. Mocking final classes or methods is something that most mocking frameworks struggle with. Because of this restriction, sometimes a good design is sacrificed.
Mocking constructors (Medium) introduces the art of mocking constructors. Is a class doing too much in its constructor? With PowerMock, we can mock the constructor and peacefully write tests for our own code.
Understanding argument matchers (Medium) demonstrates how to write flexible unit tests using argument matchers. Only verifying that a certain method was invoked is a job half done. Asserting that it was invoked with correct parameters is equally important.
Understanding the Answer interface (Advanced) demonstrates the use of the Answer interface, using which we can create some unusual mocking strategies. Sometimes mocking requirements are extremely complex, which makes it impractical to create mocks in the traditional way. The Answer interface can be used for such cases.
Partial mocking with spies (Advanced) explains the steps to mock only a few methods of a given class while invoking the real implementation for all other methods. This is achieved in PowerMock by creating spies.
Mocking private methods (Medium) covers the steps to mock and verify private methods. Private methods are difficult to test with traditional mocking frameworks. But for PowerMock, it’s a piece of cake.
Breaking the encapsulation (Advanced) shows how we can test the behavior of a private method and verifies the internal state of a class using the Whitebox class. At times, some private method might be performing an important business operation and we need to write unit tests for that method. The Whitebox class can be very handy in such situations.
Suppressing unwanted behavior (Advanced) explains how we can suppress unwanted behavior such as static initializers, constructors, methods, and fields.
Understanding Mock Policies (Advanced) demonstrates the use of Mock Policies to better manage the repeated code needed to set up mocks for a complex object.
Listening with listeners (Medium) demonstrates the steps to listen for events from the test framework. We might want to do some processing when the test method is invoked or create a report about how many tests were run, how many passed, how many failed, and so on. Listeners are a good fit for such requirements.

Sunday, September 29, 2013

How to generate UUID using Haskell - Part - 2

What is your favorite programming language?

Someone asked me this question about a month ago, suddenly I realized that, I can program in many languages, but I didn't know of a language that I am truly in love with.  At that time I was just starting to learn Haskell.

After about a month of hacking on Haskell, I am in a better position to answer this question.  Haskell is an awesome language and certainly is currently my favorite language!

I would like to ask this question to my readers:

Are you always 100% sure that, the code you have written will work without any problems, if it compiles OK?

Ever had to fix your own code because of NullPointerExceptions at run time?

With Haskell the mantra is:

If it compiles, it will work!

Over and above it, features delivered per lines of code ratio is extremely high with Haskell, i.e. more can be achieved by doing less!

I would say, learning Haskell is like falling in Love: It takes time, but once you are in it, its like the most beautiful thing :)

Alright, enough Haskell marketing, lets come back to the main topic of this post.  In the previous post we saw one approach to generate UUID's in Haskell using the system-uuid package, in this post we will look at yet another package that is well equipped to generate UUID's

How do they do it!

Haskell has a package called uuid that exposes a method to generate UUID values.  This package is a bit nicer than the system-uuid package since this package providers methods to convert UUID values to and from String values.

This package exposes methods like
  • toString - Converts UUID value to String value
  • fromString - Converts String value to UUID value
To install the uuid package use the following command
Next, generate the UUID value using this package are pretty straightforward:
  • The module Data.UUID.V1 has a method called nextUUID which will return us random UUID values, wrapped with IO monad (just like how system-uuid did)
  • However, this method also wraps the generated UUID value into the Maybe monad.
  • This is done to indicate that there is a possibility of failure while generating the UUID value.
  • Let's say because of some reason, if the UUID generation fails then, Nothing will be returned.
  • Maybe is an extremely elegant way to handle possibility of failure.
  • Once you have the UUID wrapped in Maybe and IO monad generated, you can extract the UUID value using the fromJust method
  • Let's see these steps in action, lets fire up the GHCI
This code snippet shows some extremely powerful feature of Haskell like Maybe and function composition.

That's all folks!  Till we meet again, Happy Hacking!
Have some Fun!