Distributing iOS Static Library via CocoaPods

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

I was new to cocoa pods and looked at their documentation on how to create a pod and distribute. They mainly focused on examples that involved distributing source files rather than a pre-built iOS static library. Hence I want to make a short post on how the pod spec looks like if you are shipping an iOS static library via Cocoapods.

This post does not list steps on creating pod spec and uploading it to the master repo. I will rather provide links which helped me doing that. Please read through if you already know what is cocoa pods and you have an iOS static library which you need to distribute through Cocoa pods.

If you ended up this page as a newbie to cocoa pods, don’t worry.  Refer the following links and come back.

For information on how to consume cocoa pods as well as how to create one, I found this blog very helpful – http://nshipster.com/cocoapods/

I strongly recommend to test your pods locally before pushing things to master cocoa pods repo: here is how you do that http://www.cocoanetics.com/2013/05/8130/

Assuming you are all setup with your pod specs, below are the attributes of pod spec which is vital in distributing iOS Static library

s.source_files : Specify which files need to be copied. In our case, we need to copy the the Calculator.h header file. The value of the source_file attribute is the relative path of the location of header file from the Podspec location.

s.public_header_files = Specifies the header files to include and search for. Value is the relative path of the header files and the path will be added to User Header file search path in the Xcode build settings.

s.library = the Libraries to link with in order for the static library to compile successfully. In our example, the library requires the stdc++ library. The value is the library name without appending lib as prefix. For e.g., stdc++. If you have multiple libraries as dependency, provide them as a comma separated values.

s.framework = List of frameworks that the library is dependent upon. As every project by default is linked with UIKit, Foundation, You can specify any other frameworks as a comma separated values.

s.preserve_paths = We need to specify the files to be copied during the installation. In our example we need to explicitly copy our libCalculator.a file after installation onto the clients system. The value of this attribute would be the relative path ( from the PodSpec)  of the files to be copied.

s.requires_arc = The value is either true or false. Since our example project supports ARC, we set it as true

s.ios.vendored_library = Specify the library, libCalculator.a to be copied while installing the pod

Additional attributes that might come in handy

s.dependency = Reference to another pods, where the library is dependent upon. For the simplicity of the example, I have not included any libraries as dependents.

s.xcconfig = There would be other build settings, for which there are no corresponding  attributes in Podspec. In such cases, you can use xcconfig to specify the build settings directly.

For example, to set the HEADER_SEARCH_PATH build settings you can specify them in a json style like

{ “HEADER_SEARCH_PATH” => “$(SDKROOT)/usr/include/libxml2“}

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

Here is the final PodSpec

Pod::Spec.new do |s|

s.name = “CalcLib”
s.version = “1.0”
s.summary = “Example iOS Static Library – Calculator. ”

s.description = <<-DESC
This iOS Static library is used to explain how to distribute iOS Static library via cocoapods

s.homepage = “https://github.com/bharath2020/CalcLibrary/blob/master/README.md”
s.license = { :type => “BSD”, :file => “LICENSE” }

s.author = { “Bharath Booshan” => “bharath2020@gmail.com” }
s.social_media_url = “http://twitter.com/bharath2020”

s.platform = :ios, “6.0”
s.source = { :git => “https://github.com/bharath2020/CalcLibrary.git”, :tag => s.version.to_s}
s.source_files = “include/*.h”
s.public_header_files = “include/*.h”

s.preserve_paths = “libCalculator.a”
s.ios.vendored_library = “libCalculator.a”

s.libraries = “stdc++”, “Calculator”
s.requires_arc = true

Test this Sample

I have created a test library named Calculator which calculates a^2 + b^2 + 2ab for a given values a and b. For demonstration purposes, i have internally used c++ class to perform addition and multiplication. This is to demonstrate how to supply additional dependent libraries in the pod spec file.

Here is the github link : https://github.com/bharath2020/CalcLibrary

To test the library with an example project, add below line to your pod file


pod ‘CalcLib’

and execute pod install or pod update


You can insert the following code in your example project for verification

Calculator *calci = [[Calculator alloc] init]

int result = [calci APlusBWholeSquare:2 andB:3]


Here are few references who distributes iOS Static library via cocoa pods:




Hope this Helps.

longLongValue issue in NSDecimalNumber

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

Problem: A legacy module in current project involved JSON parsing where SBJSONParser was being used. While doing performance analysis, we found out that SBJSONParser was contributing to 50% to the load time of the module. The benchmarks done here ( https://github.com/bontoJR/iOS-JSON-Performance  )  convinced us to use NSJSONSerialization, a native JSON parse in iOS 5.0 and above. Things went smooth except with the change except for the below issue


We were using 64bit number to represent primary key.  NSJSonSerialization used NSDecimalNumber for representing numbers, while SBJSONParser used NSNumber to represent numbers. 


With NSDecimalNumber, a number returned from its description or stringValue method found to be different from the value returned by longLongValue  method implementation by NSDecimalNumber.


For eg: 3924849704573025603 = 3924849704573025792


The reason is well explained here  http://stackoverflow.com/a/12421451/623569


The problem is that an exact value of an NSDecimalValue is only representable as … anNSDecimalValue.

You can get an approximate 64 bits IEE754 value with method doubleValue. When you try to use longLongValue you effectively get the result of casting to a long long int the approximate IEE754 value.


Many of the modules in our project were using longLongValue, means that we had no choice to do a Find and Replace in the source as application using this module was out in market used by many clients and the value was stored in the database.



How do I make sure the longLongValue of NSDecimalNumber be consistent with its stringValue method?



Categories in our Objective-C comes to our rescue.

By creating a Category of NSDecimalNumber and re-implementing longLongValue. this new implementation will convert the number to string using stringValue and return number of type long long using longLongValue method. Since, NSString uses NSNumber to make the conversion, the final value returned by longLongValue is equal to value obtained through stringValue method in NSDecimalNumber.


@implementation NSDecimalNumber (unsignedLongLongBug)

– (long long)longLongValue


    return [[selfstringValue] longLongValue];




A point to note here is that we are not interested in the correctness of the value in our case, rather we are trying to make the results consistent as I am only looking for the number to be unique and not using the result for any calculation. 



A word of CAUTION: Using a method in category to replace Primary class’s implementation may have unknown impact in case if there is a second category which implements the same method. In real word it depends on order in which the category is loaded and always the the method is replaced by the last category to be loaded.



Why I like Blocks?

In my last post here , I wrote about the syntactical difference between the Blocks and the C Funtion pointers. In this post I share my first hand experience on Blocks and how it changed my programming style and thinking, especially if you are not from Java / Javascript world.


In simple terms, Blocks are tiny independent code blocks that could be executed on its own. How did Blocks saved me? Lets take below code snippet as an example:


[imageDownloader downloadHUGEImage: ^(UIImage* newImage){

    [self createThumbNailForImage:(UIImage * newImage)];





[imageDownloader setDownloadDelegate: self ];

[imageDownloader downloadHUGEImage];





– (void)imageDownloader:(BBImageDownloader*)downloader didDownloadImage:(UIImage*)image


    [self createThumbNailForImage:(UIImage * newImage)];



Advantage #1: It added more readability to my code:

Everyone would know what we are exactly doing after downloading an image, where as with delegate pattern, one has to jump to definition of the delegate methods, which sometimes resides in multiple files, by then you would lose the trace of the initial method.


Advantage #2: Eliminates Delegate Pattern

The same reason as above, With Blocks, you will no more have to spend your time in retain cycle which is more common mistake made by programmer when using delegate pattern in Objective-C, (although blocks do produce retain cycles, but they are easy to detect   )



Advantage #3: Save more context info variables.

Lets take an example of usage of beginAnimation: method on UIView in Pre-Block Era.

int state_before_animation = 0

[UIView beginAnimations:@” ” contextInfo:& state_before_animation]






– (void)animations:(NSString*)animation didFinish:(BOOL)finish contextInfo:(void*)contextInfo


    //do some

int *state_before_animation = (int*)contextInfo

//change state depending upon state_before_animation




– During the execution time between start of animation  and completion of animation, we lose the scope of local variables that were available at the start. This made the necessity of carrying these variables in the form of contextInfo


– It increases the burden of maintaining the integrity of the contextInfo variable during this time, it travels between different modules and sometimes b/w the third party libraries. 


With blocks, it makes much more simpler to write:


int state_before_animation =0

[UIView animateWithDuration:0.9 beforeAnimation:^{




   //do something depending upon state_before_animation




 Isn’t it decreases your development time?


Happy Coding 🙂

UITableView Tricks – Part 2 – Infinite Scrolling

Last time I posted about the UITableView Tricks to lay the cells of the tablview in Circular fashion. It was well received by the community and thank you all for your feedback and compliments. 

I received many requests for making this circular list scroll infinitely as with UIPickerView, which means that the list repeats forever. It really makes sense just because the list itself is in circular fashion and user expect the content to repeat, without him/her having to scroll back to top.

I came across the 2011 WWDC video – Advanced Scrollview Techniques which provides the best feasible solution to support infinite scrolling. Many attempts have been made before to find a solution by having the height of the scrollview’s content size to a large number so that it takes days, if not AGES for a user to get to the end point. But it was never a complete solution.


I went a bit closer to the perfect solution and here it is. The goal here is to provide a generic solution to a UITableView while having the user/ developer to do minimum or ZERO changes. This lead me to create a subclass of UITableView, and named as BBTableView


By using BBTableView,  a developer has to do ZERO changes ( some minor changes for additional functionality, explained later ) to enable infinite scrolling. 


Behind the scenes:


 The core logic of this solution is


1. To increase the tableview content by a factor of 3, so that we make the 3 copies of the content laid one after another vertically. 

2. Whenever the top end of the scroll is reached, move the the scroll offset back to start of the 2nd copy

3. When the bottom end of the scroll is reached, we move the scroll offset back to the start of the 2nd copy minus the height of the tableview, so that we end up showing the same content as we are now.

Infinite Scrolling

This solution did bring an obstacle to my goal of making this component as a Drag-n-Drop component. i.e. Making 2 additional copies of rows provided by datasource also changes the index paths used in datasource or delegate methods that are propagated to the component user, a developer who would use this component.

This can be avoided by intercepting the delegate or datasource methods to morph the index paths exchanged between the UITableView and the its datasource or delegate methods.

Thanks Evadne Wu , for allowing me to use the interceptor component written by her.

Two  properties have been added to BBTableView,

a. contentAlignment

Allows the change the direction of the semi-circle. It supports two directions

ClockWiseScreen Shot 2012 12 07 at 9 25 33 PM

eBBTableViewContentAlignmentRight Layouts the circle Clockwise

eBBTableViewContentAlignmentRight – Layouts the circle Anti-Clockwise

b. enableInfiniteScrolling

    set YES to enable infinite scrolling. NO to reset to default scrolling behavior of UITableView


As every software, this component too have its Cons:

1. Since the issue with Index Paths resolved by intercepting delegate / datasource methods, Any additions or modifications to UITableView datasource/ delegate methods involving index path, requires a change to counterpart datasource / delegate methods implemented in BBTableView. However, on a good note, this change includes only getting the morphed index path and calling appropriate method on the receiver of Datasource interceptor.

A  sample intercepted Datasource method would look like:

(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    return [_dataSourceInterceptor.receiver tableView:tableView cellForRowAtIndexPath:MORPHED_INDEX_PATH(indexPath)];



Check the source code updated in github here https://github.com/bharath2020/UITableViewTricks

Happy Coding 🙂

Blocks Syntax and its Variants

This post is specifically to me. I am not sure why I am not able to remember this simple syntax of the passing blocks as parameter.


So here it is.. Its very similar to C function pointers

<return type> (* [<function pointer name>])( [parameter1, parameter2….])

The only difference is to replace * to ^.  <function pointer name> is name of the block, Lets call its as as <block name>.  if you are using this directly to pass a block as  a parameter to a method, then the <block name> is not needed.


For Example, You declare a method which accepts a block as a parameter like this:

-(void)performLongOperation:( void (^)(NSError *error, id result))completionBlock;

Variants of Creating and Defining a Block

a. Block definition as part of method invocation:


One would invoke the block within the performLongOperation method definition as:

NSError * error = nil;

id result = nil;




completionBlock(error, result );

The caller would look like:

  [self performLongOperation: ^(NSError *error, id result){

        //what you want to do after performLongOperation?


This is one of the way where the whole body of the block is written as part of method invocation.



b. Block as a variable OR a named Block:


If the above code snippet looks complicated (esp. if the callback is very lengthy) or if there is a need to separate the callback from the caller, then you can give a name to a block like this:

  void (^ myblock )(NSError *, id result)  = ^(NSError *error, id result){

        //what you want to do after performLongOperation?


where myblock is the name of the block. The method invocation would look like:

    [self performLongOperation: myblock];

c. Block as a custom data type

In some cases, we might want to pass a different callback functions based on certain conditions and in order to do that we can create our own custom data type using typedef.

typedef void (^my_block_type)(NSError *, id );

and create a block variable of type my_block_type which accepts two parameters of type NSError and id and returns nothing.

my_block_type validate_long_operation_result = ^(NSError *error, id result){

        //validate result



my_block_type divert_to_second_operation = ^(NSError *error, id result){

        //do second operation


Caller would look like this:

[self performLongOperation: ( should_chose_second_operation ? divert_to_second_operation :  validate_long_operation_result)];


Click Me for More Info on Basics of Blocks

Happy Coding 🙂

UITableView Tricks





Recently we came across innovative UI controls like Path and Clear controls. I am pretty amazed to see a simple UITableView and its cells in iOS, can be tweaked to get a eye-catching effects as in Clear app.  After that there came a series of controls using UITableView, but this one from raw engineering was quiet nice.


After playing with it, I revisited the nuances of UITableView and came up with this simple UI Layoout which is our topic now. Take at look at this demo




You can find the Circle View Source in GitHub


I drew this sketch quickly.



IMG 4359



I laid down some rules before I started implementing.


1. I made clear that this control will not built ground up from scratch

2. Want to leverage the full power of Dequeue in UITableView 

3. Above two rules, means I should be concentrating only on how the content is laid out to present the data in different manner to the user and make it fun.


The main task that revolves around this control is how do we lay out the table cells. I used some basic trigonometry function which find out the point in circumference of the circle.


So the heart of this control resides in this method where on the while we find out the YPosition of each cell and adding yOffset of the Scrollview’s content offset. This means that the cell would move relatively as the tableview is scrolled.


The goal is to find out the X Position which is obtained by using Circle / Ellipse Equation


y = vertical_radius * sin ( angle )

x = horizontal_radius * cos (angle)




    NSArray *indexpaths = [mTableViewindexPathsForVisibleRows];

    float shift = ((int)mTableView.contentOffset.y % (int)mTableView.rowHeight);  

    int totalVisibleCells =[indexpaths count];


    float y = 0.0;

    float radius = mTableView.frame.size.height/2.0f;

    float xRadius = radius;


    for( NSUInteger index =0; index < totalVisibleCells; index++ )


        BBCell *cell = (BBCell*)[mTableView cellForRowAtIndexPath:[ indexpaths objectAtIndex:index]];

        CGRect frame = cell.frame;

        //we get the yPoint on the circle of this Cell

        y = (radius-(index*mTableView.rowHeight) );//ideal yPoint if the scroll offset is zero

        y+=shift;//add the scroll offset



        //We can find the x Point by finding the Angle from the Ellipse Equation of finding y

        //i.e. Y= vertical_radius * sin(t )

        // t= asin(Y / vertical_radius) or asin = sin inverse

        float angle = asinf(y/(radius));


        //Apply Angle in X point of Ellipse equation

        //i.e. X = horizontal_radius * cos( t )

        //here horizontal_radius would be some percentage off the vertical radius.

        //percentage is defined by HORIZONTAL_RADIUS_RATIO

        //HORIZONTAL_RADIUS_RATIO of 1 is equal to circle

        float x = (floorf(xRadius*HORIZONTAL_RADIUS_RATIO)) * cosf(angle );



        frame.origin.x = x ;

        if( !isnan(x))


            cell.frame = frame;






Couple Macros found in source code which you could control”

  • HORIZONTAL_RADIUS_RATIO – defines the ratio between Vertiacl and horizontal radius. HORIZONTAL_RADIUS_RATIO of value 1 is equal to circle
  • HORIZONTAL_TRANSLATION – Helps translate the position of whole Circle / Ellipse i.e the position of the cells 

You can find the Circle View Source in GitHub





A major improvement has been made to this project. Please read UITableView Tricks – Infinite Scrolling  to know about the new features and improvements.





This Post has been featured in 




Have modified the source code to support the inverse form of the circle i.e the circle can be turned toward right as shown in figure by setting the CIRCLE_RIGHT_DIRECTION macro to 1


Screen Shot 2012 07 19 at 11 03 55 PM





Hope you enjoyed this. Let me know your comments.

Happy Coding 🙂

Capturing Exceptions while debugging

This one is a simple but could be time-saving 🙂

Scenario: If you are debugging and caught with awkward situation where the application crashes with an exception, like NSInvalidArgumentException and so on, but never take you to the place in the code where the problem exists.



Remember, This solution is for Xcode 4.2.1 for Lion.

1.  Select View->Navigators->Show Breakpoint Navigator

Screen Shot 2012 02 22 at 4 42 58 PM

2. At the Bottom-left cornet, Click the ‘+’ symbol and Select ‘Add Exception Breakpoint’ Menu

Screen Shot 2012 02 22 at 4 43 20 PM

3. In the popped-up window you may select [All | Objective-C | C++ ] options to select what type of Exception should the execution stop.

Screen Shot 2012 02 22 at 4 44 15 PM


4. Click Done.

Restart your debug process and you should see the line of code that is causing the hassle for you 🙂


Courtesy: Apple Developer Document.



[self class] and static methods in Objective-C

Its been 5+ years of Objective-C programming and If I turn back and see, I have still a lot to learn.

I recently was working on a project, where a small design mistake look costlier. To overcome that, I had to override a set of static methods.

Let me give some insight into what happened before this.


I have seen many people use [self class] method in a static method, and I had always thought (my fault, i did not test it 🙁 ) that this would be always equal to the class name where the method is defined. But, I was wrong


So I had the following static method to create the Message model object




return [[[BBMessage alloc] init] autorelease];




BBMessage *newMessage = [BBMessage newMessage];




This method was widely used to create the BBMessage object throughout the application. As it turned out be at the near end of the project, I had to add a subclass of BBMessage named BBHistoryMessage. However, the difference between BBHistoryMessage and BBMessage was a couple of  attributes in BBHistoryMessage, but their creation using method messageFromDictionary: remained same.

However, since it had [BBMessage newMessage] statement, the object created by messageFromDictionary: always created BBMessage instance rather than BBHistoryMessage’s instance

This is when I realized that replacing the appearances of BBMessage class name with [self class] as the [self class] would return the name of the class which invoked the method


For eg: if the BBHistoryMessage class  is used to invoke messageFromDictionary: then [self class] will be BBHistoryMessage class and hence newMessage would be creating BBHistoryMessage Class.



iOS Open Folder Animation

As I was fiddling with my iPad,  Open Folder Animation in iOS caught my attention. After giving it a serious though on how to achieve it, It looked Trivial.

iOS Folder View


Let us get together to write a piece of code which does this cool animation.


1. Plan


We can achieve this using 3 Main Layers

1. Layer -1 (Main View) : The Lowest layer contains the main screen which stores the main content

2. Layer -2  (Folder View): The Folder View, which hosts the Folder Icons. Once the Folder Opens, This is the only view which is active accepting the Touch Event. This layer resides above Layer-1

3. Layer-2.1 (Arrow ) : The Arrow, which points to the selected folder. This is movable on x-Axis.

4. Layer-3 (Layer to host Bottom part of Main Content View) : This layer hosts the bottom part of the Main Content View (Layer -1) i.e from point where Folder View ( Layer-2) occupies to the end of the Main Content View. This Layer is place above the Folder View (Layer-2 ) in terms of Level. In Terms of position on screen, this layer is placed just below the Folder View(Layer-2)


2. Execution

We can achieve Open Folder Animation effect in 3 Simple Steps

STEP 1: Capture the Main View Content into an image

  • Capturing Main View Content Image can be achieve using renderInContext: API. as shown in code snippet below
  • Clip the Main View into two parts, One part is the visible portion above the Folder view and rest of the image would be hosted in Layer -3. The Trick used in sample code below to avoid the cutting of the image into two parts, is by setting the Layer-3 bounds, such that it should hide the top portion (Part-1) of the Main Content view.




//capture the main content view

[mMainBackgroundView.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *backgroundImage = UIGraphicsGetImageFromCurrentImageContext();

[mBottomPartOfMainBackgroundView setImage:backgroundImage];

//set the bounds such that the we hide the part of the main content image, which is visible just above the Folder View.

//This gets the continuation effect on the image once the folder view appears on screen

[mBottomPartOfMainBackgroundView.superview setBounds:CGRectMake(0.0, selectedFolderPoint.y + mSelectedArrowTipView.frame.size.height, mMainBackgroundView.frame.size.width, mMainBackgroundView.frame.size.height)];



STEP 2: Layout the Folder View(Layer 2 & 2.1) and Bottom Part Of Main Content View (Layer -3)

  • Folder View and Arrow View are grouped in Single View.
  • Place The Arrow View such that it is right below and to the Center of the Tapped Folder Icon Tapped
  • Place the Folder View Just below Arrow View



//Place the Folder View Just below Arrow View

CGRect folderViewFrame = [mFolderView frame];

folderViewFrame.origin.y = floorf(selectedFolderPoint.y);

[mFolderView setFrame:folderViewFrame];

//making sure the View which displays bottom part of Main Backgorund View is just below  the Folder View

CGRect maskFrame = mBottomPartOfMainBackgroundView.superview.frame;

maskFrame.origin.y = folderViewFrame.origin.y + mSelectedArrowTipView.frame.size.height;

mBottomPartOfMainBackgroundView.superview.frame = maskFrame;

//Place The Arrow View such that it is right below and to the Center of the Tapped Folder Icon Tapped

[UIView setAnimationsEnabled:NO];

mSelectedArrowTipView.center = CGPointMake(selectedFolderPoint.x, 0.0);

CGRect arrowFrame = mSelectedArrowTipView.frame;

arrowFrame.origin.y = 0.0;

mSelectedArrowTipView.frame = arrowFrame;


[UIView setAnimationsEnabled:YES];



STEP 3- Push The Layer-3 which hosts the other part of the Main Content View



//Push The Layer-3 which hosts the other part of the Main Content View

CGRect maskFrame = mBottomPartOfMainBackgroundView.superview.frame;

maskFrame.origin.y = mFolderView.frame.origin.y + mFolderView.frame.size.height;

mBottomPartOfMainBackgroundView.superview.frame = maskFrame;



Thats it !! The above 3 steps would be called upon tapping a Folder  Icon as show in below code snippet



//get the center point of the tapped folder

CGPoint selectedFolderPoint = CGPointMake([sender center].x, [sender frame].origin.y + [sender frame].size.height);

if( mFolderView.hidden )//if folder is not opened


//open folder animation

//STEP 1: Capture the Main View Content into an image

[self captureImageFromPointAndSetupMaskView:selectedFolderPoint];

//STEP 2: Layout the Folder View(Layer 2 & 2.1) and Bottom Part Of Main Content View (Layer -3)

[self layoutBottomPartOfMainViewRelativeToPointInMainView:selectedFolderPoint];

[UIView beginAnimations:@”FolderOpen” context:NULL];

[UIView setAnimationDuration:0.5];

[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

//captures the main background view’s image



//STEP 3- Push The Layer-3 which hosts the other part of the Main Content View

[self layoutFinalFrameOfBottomPartOfMainContentView];

[UIView commitAnimations];


else {

//close folder animation

[UIView beginAnimations:@”FolderClose” context:NULL];

[UIView setAnimationDuration:0.5];

[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

[UIView setAnimationDidStopSelector:@selector(animation:didFinish:context:)];

[UIView setAnimationDelegate:self];

//restore the layout and hide the folder view after animation

[self closeFolder:selectedFolderPoint];

[UIView commitAnimations];




3. Result

Download the Full Source Code Here : iOS Open Folder Animation.zip

A Video of the Sample Code can be found here: iOS Open Folder Animation Video


If you like this post, Please leave your feedback / comment and Share this (See below for sharing options) to spread to all others who might be interested 🙂

Happy Coding 🙂

How to compare objects of your custom classes?

[This post is intended only for audiences with Basic knowledge in Objective-C]

With Cocoa / UIKit framework has built-in support for comparing objects like NSDate, NSString, NSData, NSNumber and few others which would help us to identify whether two objects are EQUAL, GREATER THAN or LESSER THAN the other object. This in-turn is used in cases like sorting, searching.


We would like to see how the same can be achieved for the custom classes we write, where we can specify the Equality condition by our own.

By default, NSObject class allows us to determine equality between two objects whose class is derived from NSObject through

isEqual: method,

where Apple documentation defines it as

This method defines what it means for instances to be equal. For example, a container object might define two containers as equal if their corresponding objects all respond YES to an isEqual: request. See the NSArray, NSDictionary, NSString and NSData class specifications for examples of the use of this method.

If two objects are equal, they must have the same hash value. This last point is particularly important if you define isEqual: in a subclass and intend to put instances of that subclass into a collection. Make sure you also define hash in your subclass.



In short, At NSObject (root class) level, two objects are said be equal

  • if their hash value are same
  • two objects have same address.

Well this may not be the case when we write our custom class,  for example,  two NSString objects might have different  pointer addresses, but have same string value. Hence, one must override hash method and isEqual: method of NSObject. NSString class would have hash and isEqual defined as below

– (NSUInteger)hash


//return the hash value generated from the string.




// return strcmp ( [self’s cString] , [otherObject’s cString] )



Where do I apply this?

Well, if you encounter a situation where you have an array (or in general collection) of Employees for eg, and you would want to remove an employee of particular ID, then you can do it with a single call like this. This would save you from writing an search algorithm.

Employee *employeeToRemove;

[myEmployees removeObject: employeeToRemove]; // assuming myEmployees is of type NSMutableArray

As Apple document says, removeObject and its variants (see below list for variants) would pick the object to remove for which isEqual: would return TRUE

  • – removeObject:
  • – removeObjectIdenticalTo:
  • – removeObjectIdenticalTo:inRange:
  • – removeObjectsInArray:
  • – indexOfObject:
  • – indexOfObject:inRange:
  • – indexOfObjectIdenticalTo:
  • – indexOfObjectIdenticalTo:inRange:


Another method that does fall in this category, is compare: method (actually you can give a custom name to this method ) whose signature is


NSComparisonResult is an enum with values  as below

enum {

NSOrderedAscending = -1,





With this method implemented in your Custom class (for example, Employee class), you can sort your objects in a collection (NSMutableArray , NSArray) with a single statement

[ myEmployee sortArrayUsingSelector(compare:)];

Other variants where this strategy can be used are

– sortedArrayUsingSelector:

– sortUsingSelector:


Hope this tutorial find useful for you.

Happy Coding 🙂