Porting to Swift from Objective-C

Finally its time to take swift language on a serious note. All the examples in the blogs have been converted to swift language. With me having worked with a bit of Java(Android), Python and javascript, I thought i could speed up my learning by porting one of the existing Objective-C project where I can touch upon all most often used elements

Note: This is not a Introduction to Swift programming post. I would suggest you read this, if you are an seasoned Objective-C developer and want to see a sneak peak of what Swift has to offer you.

In this post, I will be walking you through the differences/modifications I found when porting from Objective-C to Swift ( Don’t mistake this with Convert-to-swift feature in Xcode). The differences would be more of a design / semantical in nature and not one-to-one mapping of syntax. Fo e.g. I will not say that to declare a class, you use class keyword  in swift instead of @interface in Objective-C. These differences are nothing new in any object oriented languages. However, Objective-C being dynamic typed language, It need a perspective change to program in swift, especially if you have been coding in Objective-C for a long time. 


#1 You don’t have to subclass all your classes from NSObject

“NSObject is root of all the classes. It provides methods for things like alloc, init and release. Objective-C is all about sending messages to other objects – so NSObject exists to provide this basic functionality” – from http://stackoverflow.com/a/12991946/623569

#2 Immutability is let, Mutability is var. Always start with ‘let’

Its takes time to get used to using let or var keywords to declare a variable, and it takes more time to know that mentioning Data type is not mandatory. But the key thing, is swift compiler does not complain if you declare a variable using var and does not modify it. This means, that you will end up with swift compiler generating a lot of code to support mutability of these variables which directly affect overall performance.

@iDeekshi got me a nice tip – Start with declaring a variable as let and let the compiler complain when it is mutated.

#3 Yet another block syntax 

It took a lot of time for me to practice the block syntax in Objective-C. In swift, it looks like I am back to square one. Flower braces ‘{‘ starting before the parameter declaration, and writing the function definition after ‘in’ keyword is something I am still getting used to.  Here is it how it looks:


[capture list] (parameters) -> Return Type  in




#4 Use === to compare two object pointers

Comparing two object pointers studentObj == otherStudentObject will now need to be studentObject === otherStudentObject. Its a good move.

#5 You no longer need NSDictionary to send more than one value. Swift introduces Tuples to return multiple values

This has been a long time ask from me. I am glad we finally have it. You can create a type with just defining all the values and its types in a parenthesis as show below

func getMinAndMax( numbers : [Int] ) -> (min : Int, max : Int ){ 

   var max = numbers[0] , min = numbers[0] 



return (min,max)



#6 Initialize all your variables in the class before calling super init.

class Person{

var name : “”

init() {

name = “<unknown>”



class Teacher : Person{

var subjects : [String]

init() {

 //we have to initialize the subjects before calling super init

subjects = [“English” , “Kannada”]




This is not the complete list. I have only picked those which I thought had a striking difference from what we are used to while programming in Objective-C. 

Let me know your experiences while porting Objective-C to swift code through comments.

Happy Coding :-)

Thread-safe array in Java

Here is the template class to demonstrate the Thread-safe Array which can store any Java Object Type

Tools to Reverse Engineer Android APK

Here is the list of compiled tools that may be used to reverse engineer an Android APK. None of them are discovered by me. Rather I found these through stack overflow and other blogs while trying reverse engineer an Android APK, where I had to find out an issue with no source code available.

 The credits have been added in comments.

Hope this Helps.






Android: Turning Flash ON/OFF

After playing with Android OS and messing with different IDE like Eclipse, IntelliJ, I finally settled down with Android Studio for Android App development. I definitely found it useful for the beginners who had no exposure of Java or Eclipse world.

With the newly found Euphoria, I thought I should start of with Simple Android program, Playing with Flash Light on Android Devices. But, It turned out to be not so straight forward, after following the developer documents. It once again proved that, the fragmentation issue Android was facing, where the solutions on stack overflow when you quickly search “Flash Light API in Android” look so obvious, but does not work on most of the devices

Here I am sharing the one which I got to work on Google Nexus 5, Android Lollipop. The Key here is to use setPreviewTexture() method on Camera object. 

Hope you find it useful.


Distributing iOS Static Library via CocoaPods

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“}

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

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.



Git – Basic Terminal Commands Checklist

I was observing a lot of traction from the developer community about the Git and Github and last year I got a chance to use the Git, majorly because of the woes we had using SVN ( subversion ) as our source control  in our team where most of the members are working remotely. I was amazed to see the power of Git but the learning curve was very steep, especially if you are a long time SVN user. I chose to use terminal commands to operate Git instead of a GUI tool so that it would help me know how Git operates behind the scenes which is masked by many GUI tools out in the space.

I started preparing an Appendix of commands of myself which I would use on a daily basis and most of my usage of commands are recorded in this list. Since, Its been close to year where I have made this checklist and updated as I found new usage scenarios, I thought i would share this back to community and to the newcomers who are entering into Git world, to make their Git transition smoother.


  • I assume that the readers / users of this checklist  have the conceptual details on how who Git operates.
  • I always referred remote repository as origin ( as most of the time I used only single repository and git names it as ‘origin’ by default ).
  • I have most of the times tested these commands in Mac OS X 10.8, however I would assume you know why you are using these commands and I would not be responsible for any data loss resulting from usage of these commands.

I have organized the following commands based on the usage scenarios:

1. Basic Update and Commit 

   a. Check the status of git  

git status

   b. Adding Files

git add <filename>


git add <regular expression>

    c. Commit – only updates the Local repository and does not push to the cloud

git commit -am “Commit Message”

git commit -m “Commit message” <filename> 

    d.  Update to remote repository

git push <remote name> <branch>

By Default <remote name> would be origin, if no branch is specified, then it will be pushed to master.


2. Remove from staging == remove from svn tracking

git rm -r –cached <file path>


3. Git Branch 

 a. Creating a branch

git branch <branch_name>


git checkout -b  <branch_name>


b. List all branches

git branch 

c. List all branches in remote repository

git branch -r


git fetch && git branch -r


d. Merging a branch


1. To commit and push all the changes made in this branch to remote

//Commit all the modified files

 git commit -am “<Commit message>”   

git push origin <branch name>


2. Switch to destination branch where u need to merge your changes. 

For eg. If you want to merge in Feature 1 in master branch, then switch to master by ‘git checkout master


git merge <branch_name>

git merge –no-ff <branch_name>


c. Deleting a branch in local repository

git branch -d <branch name>


d. Deleing a branch forcefully on local repository

git branch -D <branch_name>

e. Deleting a branch on remote repository

git push <remote> :<branch _name>

f. Download a branch from the repository 

 (sometimes you need to execute ‘git fetch’ command before executing this command )

git checkout -t origin/<branch-name> 

4. Ignore New Files or Never track

– Place .gitignorefile in Git root directory

– Add the file path or wilde cards for e.g.,  *.xcodeuserstate entry for example using vi editor or any text editor. You can add each file to be ignored in a new line

– save the .gitignore file

– this will take effect only to the new files. if you want to ignore an existing file. do a git rm –cached <filename> and follow the above steps.

Please let me know through comments in this blog if there are any faulty usage of these commands, so that I could rectify it.

I will try to update this post as and when I find some new commands. Please let me know if you find this useful.

Happy Coding :)

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 :)