iOS Development

Creating Singleton…

Singleton classes are unique design patterns which are greatly used for storing data in memory for global use in the application. A Singleton class can have only one instance and that same instance is returned when the initializer is called. Generally the designated intializer (the initializer which makes the [super init] call) is internally called in a class method (initializer) which creates a static instance of the class and returns it. Generally this initializer is prefixed with “Shared” e.g. SharedManager etc.

Steps to Create Singleton

Let’s consider for a moment that we are going to create a singleton class named “MySingleton” and following are the exact steps you will need to follow in a ARC environment.

Step 1. Method and Property Declaration

  1. Declare the required properties in the header file
  2. Declare the initializer class method name



@interface MySingleton : NSObject {
NSString *someProperty;

@property (nonatomic, retain) NSString *someProperty;

+ (id)sharedMySingleton;


Step 2. Method Implementation

Inside the class method sharedMySingleton –

  1. Declare a static variable named sharedMySingleton
  2. Use GCD command “dispatch_once_t” to call the designated initializer method once and assign the same to sharedMySingleton
  3. Return the static variable sharedMySingleton

Implement the designated initializer –

  1. Assign the [super init] to self as is done in designated initializers
  2. Initialize the variables declared in the header file


+ (id)sharedManager {
static MySingleton *sharedMySingleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMySingleton = [[self alloc] init];
return sharedMySingleton;

– (id)init {
if (self = [super init]) {
someProperty = [[NSString alloc] initWithString:@”Default Property Value”];
return self;

This class will return the same instance when ever the “sharedMySingleton’” is called and you have got a Singleton!

Update: Mattt Thompson has put together a nifty little code snippet here for your Xcode to create Singleton classes.


iOS Development



It may be right that the @NSAutoreleasePool has a lot to discuss, but as of now I think the most valuable inputs for me are the following two:

1. When we use the AutoreleasePool?

If you are running a run-loop it should be managing an autorelease pool automatically for you; it should create a pool at the top of the loop and drain it at the end of each pass through the loop.

You only need to cycle one yourself if you have other stuff going on outside of the runloop.

2. When is AutoreleasePool drained?

The Application Kit creates an autorelease pool on the main thread at the beginning of every cycle of the event loop, and drains it at the end, thereby releasing any autoreleased objects generated while processing an event.

3. Difference between “release” and “drain”?

In a reference-counted environment, releases and pops the receiver; in a garbage-collected environment, triggers garbage collection if the memory allocated since the last collection is greater than the current threshold.

If your system has a garbage Collection, then -drain send message (objc_collect_if_needed) for GC. If you haven’t GC, then drain = release

Hope this helps!

iOS Development

Setters & Getters in Objective C


The objective C setters and getters are never used, thanks to the @synthesize keyword bestowed upon us like God’s grace by the good fellows who created the language. Though there is rarely any chance of using it, its good to know how to write it for the apocalypse day when @synthesize is not working (hope it does not come!)

The Getters are easy, simple fellows with minimal code and goes as following:

//MyClass.h file

@interface MyClass: NSObject
    NSString *text;

//MyClass.m file

-(NSString*) text
   return text;

Setters are however a little tricky:

-(void) setText:(NSString *)textValue
    if (textValue != text)
        [textValue retain];
        [text release];
        text = textValue;

Quick Facts:

  1. The above method is the setter and is supposed to set the value to the variable which is passed to it
  2. The “if” condition is put there to avoid unnecessary code execution in case the old value and new value are the same
  3. To make sure “textValue” stays with us for a considerable amount and we do not lose it before proper assignment, we pass “retain” message to increate it’s retain count by 1
  4. We liberate “text” of its old value by passing “release” message to it
  5. Finally we assign the new value to text
iOS Development

Logging in Objective C

Logging has always played a very vital role in all kinds of programming platforms and languages. In objective C the most  commonly used method of logging is, as we all are quite well aware of, NSLog(). Though it may seem a little naive for experienced developers to see the usage of NSLog again, but for the new comers I would mention it shortly. However, human beings are curious creatures and never have settled down with anything. So, there are better ways of logging than NSLog. Let us see what these logging mechanisms are:

  • NSLog

    The NSLog, though being memory heavy, is the most commonly used mechanism for logging. The syntax is as follows:

    NSLog(@”%@”, @”message goes here”);
    NSLog(@”The %d iteration of this loop provides data: %@”, iteration, data);

  • Conditional NSLog for Debugging Purpose

    Despite of its simplistic nature, NSLog adds memory overhead and is not at all recommended to be kept in release mode of applications. This is not only because of the associated memory load and leak issues, but also due to the most common error of accidentally leaking proprietary and sensitive data to unauthorized users. But we can not simply live without NSLog (we can, but more on that later). Hence the ideal condition would be to enable NSLog when application is in “debug” mode and switch it off when application is released i.e. in “release” mode. To achieve this the best way is the following:

    Step 1: Add the following code to the Appname_prefix.pch file

    #ifdef DEBUG
    #    define DLog(…) NSLog(__VA_ARGS__)
    #    define DLog(…) /* */
    #define ALog(…) NSLog(__VA_ARGS__)

    Step 2: Go to “Schema” and set the current schema to Debug

    Step 3: In the build configuration “Other C Flags” key add –DDEBUG

    That’s all. Now, when you are building the application and need to log anything which you only want to display in debug mode, use DLog(). When the application will be run in “release” mode, the DLog will print nothing. Also if you need anything to be printed irrespective of the configuration, use ALog in this case. The syntax for DLog and ALog would be exactly as NSLog().

Pro Tip: An unexplored horizon – Apple System Logs (ASL)

In most of the cases when the application is launched in the App Store and users are using the app, and unfortunately, the application crashes, there is no way to receive this kind of information without a lot of effort. A few days back, it was impossibly difficult to get access to the crash logs, warning logs etc. However, recently Apple has enabled the “Apple System Log” (ASL) which was there in OS X, in iOS also. Accessing the ASL, now we can get all 7 levels of logs and can easily post them to any server and set up a automatic logger system like Crittercism (however, Crittercism does it too elegantly).

ASL is a low level C API used to access the Apple Server Logs and use them in applications. Here is a quote from the manual page:

 The new API allows client applications to create flexible, structured messages and send them to the syslogd server, where they may undergo additional processing. Messages received by the server are saved in a data store (subject to     input filtering constraints).  This API permits clients to create queries and search the message data store for matching messages.

More details on ASL can be found in the following links:

Information Source Blogs:


Multiple Inheritance in Objective C


Multiple Inheritance in Objective C is not supported. The reason for not supporting this mechanism might be the fact that it would have been too difficult to include in the language or the authors thought it is a bad programming and design decision. However, in various cases multiple inheritance proves to be helpful. Fortunately objective C does provide some workarounds for achieving multiple inheritance. Following are the options:

Option 1: Message Forwarding

Message Forwarding, as the name suggests, is a mechanism offered by Objective C runtime. When a message is passed to an object and the object does not respond to it, the application crashes. But before crashing the objective c runtime provides a second chance for the program to pass the message to the proper object/class which actually responds to it. After tracing for the message till the top most superclass, the forwardInvocation message is called. By overriding this method, one can actually redirect the message to another class.

Example: If there is a class named Car which has a property named carInfo which provides the car’s make, model and year of manufacture, and the carInfo contains the data in NSString format, it would be very helpful if NSString class methods could be called upon the objects of Car class which actually inherits from NSObject.

– (id)forwardingTargetForSelector:(SEL)sel


    if ([self.carInfo respondsToSelector:sel]) return self.carInfo;

    return nil;


Option 2: Composition

Composition is a cocoa design pattern which involves referencing another object and calling its functionalities whenever required. Composition actually is a technique for a view to build itself based on several other views. So, in Cocoa terminology this is very similar to Subclassing.

@interface ClassA : NSObject {




@interface ClassB : NSObject {




@interface MyClass : NSObject {

  ClassA *a;

  ClassB *b;


-(id)initWithA:(ClassA *)anA b:(ClassB *)aB;




Option 3: Protocols

Protocols are classes which contains method to be implemented by other classes who implement the protocol. One class can implement as many as protocols and can implement the methods. However, with protocols only methods can be inherited and not the instance variables.

iOS Development


Recently we have been experiencing a lot of visions – visions that promise to change the world, visions that promise to metamorphose the living real world as we know it, into something sci-fi. Beautiful girl walking through the streets with transparent virtual screens in her front displaying critical information (there goes the chance for boys looking at her face, sympathy!), people waking up in the morning as the glass window changes its colour from opaque to transparent to let the sunlight come in and wake them up (is there an option to override this? I only slept at 3 o clock!), cars having sleek glass dashboards that displays every information the driver needs (or does not) to drive the car. All of these fancy stuff is mesmerising us, inspiring us to create something that will change the world. And like God’s approval to this change, futuristic technologies are becoming open sourced, letting millions of developers being empowered to take up the responsibility to change the world. Now people cannot say – “I wanted to change the world, but God did not make it open source!”.

So, it is a golden era or technology. The digital age. But what’s the future? We are living it now. Every single day we live the future of yesterday, is that not? I remember watching “Minority Report” with my wife (then girlfriend) back in Kolkata and never did it cross my mind to replace the face of Tom Cruise with Pranav Mistry (they don’t look alike at all!). But it’s the present. And as the saying goes – “Yesterday was history, tomorrow is a mystery. But today is a gift. That’s why it is called “Present (Thanks to Kung Fu Panda movie)”. We are experiencing the gift.

But when talking about future, it’s quite difficult to describe. At least now. Because, we would be talking about the future of future! Well, who will stop us to speculate? One interesting trend I have observed is – when some new technology or gadget comes into market, people become obsessed with it. People work for it, instead of – it working for people. Remember the time, when iPhone came into market? People were creating apps for iPhone. By this, I mean, apps that will look great in iPhone, perform great in iPhone, “Consumers will have an engrossed experience when playing this game in iPhone” – was what developers and marketers were saying. But now, people have come out of that obsession. Now, apps are being created leveraging iPhone. “Leverage” is not a respectful term. If you respect Mercedes Benz S Class, you cannot “leverage” that to do something. So, people balanced themselves, not being disrespectful as well as “leveraging” the new technology is what they did. Similarly, we can speculate the future is — leveraging “surface technology” people may be doing something in near future. Just an example! But more and more people are coming out of devices – “engrossed” is not a word they are looking for anymore, “Virtual Reality” is now a historic term. People want Augmented Reality. People love their world, and want to fill up its limitations with augmented information. The applications that the future will offer will relate to this. Be it the sixth sense technology, be it the classic Augmented Reality.

The most beautiful God gave us, is our mind. (heart does not do anything other than keeping you alive – biologically speaking). What’s the second most beautiful one? What did you say? – Eyes? Hmm… I respectfully disagree. The second most beautiful thing is – arguably—our hands. People can perform tremendous variety of work with the two hands. Using their hands, people want to feel the world, touch the world, understand the world. Hands gives us perception, drives us to imaginative thinking. Steve Jobs, may he rest in peace, respected hands. Here came the iPhone. So, the future of future will speculatively, take the experience out of the cheap or expensive gadgetry – take to the real living world. People will use applications which will be experienced with all 5 senses, (read that — 6 senses) into the real world. That will be the future. Have you ever seen an app which will let you taste a recipe? An app that will let you smell the beauty of a flower? Future will bring that to you. As a bottom line, in future people will satisfy their six senses with a surrogate army of applications which will live among us in the real world. That’s where we will be going.

What did you say? Impossible? Let’s hear your side of the story.


On Technical Writing

Very recently, I was looking for some technical articles and scholarly papers on Augmented Reality. While searching, I came across a few very interesting articles, which ranged from personal blog entries and semester research papers to PhD thesis. I wondered, when we write in blogs and we write in a semester thesis paper, we have different type of mindsets, totally different objectives. Interestingly, I have seen the thesis paper becoming more interesting than the blog for the same topic in one scenario.

Technical writing is something that cannot be achieved overnight. Your first technical article, no matter how much expertise you have on the subject, is bound to be the least interesting article for the readers if you have not done your home work. Because, in technical writing you not only have to concentrate on subject matter (otherwise no point writing the article, isn’t it?) but also, have to maintain the balance of reader interaction, punch in some humor, balance the information presentation style and many more things. But how will you achieve those? Only through experience. I am not discouraging the idea of reading books on technical writing, having some courses too, in fact I recommend those and do that myself. My point is that- do not wait until you know everything about writing. Just start it!

In Bengali culture, there is a very popular idiom which means “sometimes the preparation of a work exceeds the effort needed for the work itself” and I believe it’s very true for writing, be it technical or nontechnical.  But sometimes we spend the effort on wrong things, like searching for the perfect word processor, choosing the right font, finding a lot of articles- downloading them- and not reading them etc. Here’s a small quotation from Mark Pilgrim from Google who is a writer of 4 books and a great advocate of open source software:

 I’m a three-time (soon to be four-time) published author. When aspiring authors learn this, they invariably ask what word processor I use. It doesn’t fucking matter! I happen to write in Emacs. I also code in Emacs, which is a nice bonus. Other people write and code in vi. Other people write in Microsoft Word and code in TextMate+ or TextEdit or some fancy web-based collaborative editor like EtherPad or Google Wave. Whatever. Picking the right text editor will not make you a better writer. Writing will make you a better writer. Writing, and editing, and publishing, and listening – really listening – to what people say about your writing. This is the golden age for aspiring writers. We have a worldwide communications and distribution network where you can publish anything you want and – if you can manage to get anybody’s attention – get near-instant feedback. Writers just 20 years ago would have killed for that kind of feedback loop. Killed! And you’re asking me what word processor I use? Just fucking write, then publish, then write some more. One day your writing will get featured on a site like Reddit and you’ll go from 5 readers to 5000 in a matter of hours, and they’ll all tell you how much your writing sucks. And most of them will be right! Learn how to respond to constructive criticism and filter out the trolls, and you can write the next great American novel in edlin.


So, as he rightly points out, if you are interested in writing, don’t want for the perfect moment to come, just start writing! Happy writing!