Friday, November 22, 2013

What is @synchronized directive in Objective C?

In a multithreaded environment if more than one thread tries to access same memory address may cause a Race Condition”, to avoid such kind of conditions you should use “Mutex Lock(Mutual Exclusion)” nothing but blocking or restricting or locking n number of threads to access same memory address or content at a same point of time and allowing only one thread at an instance of time.
This can be achieved in Objective C by using @synchronized directive.

Generally while implementing Singleton design pattern or class you will see some kind of code snippet like below in any iOS projects,

        if (singletonObj == nil)
            singletonObj = [[self alloc] init];
        return singletonObj;

In the above example if suppose at a particular instance of time, if two different class tries to call getSingletonInstance method then if you don’t manage thread safety then a Race Condition will occur, so as to avoid such kind of exceptional conditions you need to use @synchronized directive.
Here whenever a thread reaches this line of code, @synchronized directive will check whether any other thread is already accessing self, if some thread is already accessing it will just block the current thread until and unless the processing thread will finishes its task.

At this point you might be thinking that why do we need to use threads? & why we want to manage threads?
Here is the answer,
- Basically a thread is an instance of a Process, A process may have n number of threads (we can say threads are children’s of a process)

why do we need to use threads?
In Software Programming we need to take care of CPU resources optimizations so that the performance of our application can be increased. If we consider any iOS application basically there will be a main thread for each application where exactly the app starts and all the UI manipulations has been taken care by this main thread.

In this kind of environment suppose say an example, if you are downloading an image from a remote server through a web-service (ex: REST) call, then if you perform this task on main thread then until and unless you get the response from the server your UI will become hang, so always this kind of asynchronous tasks should be handled by separate threads so as to utilize CPU, system resources properly and to increase your apps performance.

why we want to manage threads?
- Every thread of a process has equal access to your application resources to fetch, modify or manipulate.

- Each thread will not make sure that how long it will run and when it will finishes its task.
So it’s a programmer's responsibility or the one who creates a thread its his/her responsibility to manage threads.

Advantages of using multiple threads
- Use of multiple threads will reduce CPU waiting time.

For additional information on synchronization you can refer Apple’s official documentation in following URL

Hope this is helpful, any comments or suggestions are acceptable.

Thursday, November 21, 2013

iOS App life cycle

Today will see the iOS App life cycle, mainly on
1) The App Launch Cycle
2) The View Controller Life Cycle

1) The App Launch Cycle

Lets see as soon as you tap on any application icon to open any iOS app in your device springboard what will happen,

- As part of the launch cycle, the iOS system creates a process and main thread for your app and calls your app’s main function on that main thread.

- The default main function that comes with your Xcode project promptly hands control over to the UIKit framework, it will initialize your app and prepares it to run.

Below flowchart (diagram from Apple’s developer docs: will show the sequence of events that occurs when an app is launched into the foreground

The main function’s main job is to hand control to the UIKit framework.

2) The View Controller Life Cycle

Now lets see once your app is launched then say your first screen (Root/Home View Controller), how it will load in to the screen in other words the view controller life cycle hierarchy,
If you are creating your UI or View programmatically then the first method which gets called is loadView, followed by viewDidLoad -> viewWillAppear -> viewDidAppear  and while moving to the next screen or view Controller the hierarchy of methods are like viewWillDisappear -> viewDidDisappear -> viewDidUnload  

Note: In iOS 6 and later, viewDidUnload method is deprecated since views are no longer purged under low-memory conditions.

viewDidLoadCalled only once during the initial load of interface builder(.xib) file. Initial set up of view controller can be taken care here.

viewWillAppear – This method gets called just before your view appears or renders on screen every time when you navigate or switch between different views. Suppose if you want to update your view different while switching back and forth based on some requirement for that kind of dynamic changes to the views can be done here.

viewDidAppear – Once your view loads completely on screen this method gets called and here you can handle further UI or functionalities w.r.t your view controller like database call or whatever you want to do after loading your view.

viewWillDisappear - This method is called before the view is actually removed and before any animations are configured. Notifies the view controller that its view is about to be removed from a view hierarchy.

viewDidDisappear - This method notifies the view controller that its view was removed from a view hierarchy, here you can perform additional tasks associated with dismissing or hiding the view.

viewDidUnload - Called when the controller’s view is released from memory. In iOS 6 and later, clearing references to views and other objects in your view controller is unnecessary. In iOS 6 and later, viewDidUnload method is deprecated.

 Hope this post is helpful,any comments or suggestions is acceptable.

Tuesday, November 19, 2013

The most important design patterns in iOS

Today lets see the most important basic design patterns in iOS,

design pattern solves a common software engineering problem. Patterns are abstract designs, not code. When you adopt a design, you adapt its general pattern to your specific needs. No matter what type of app you’re creating, Understanding design patterns helps you use frameworks more effectively and allows you to write apps that are more reusable, more extensible, and easier to change.

The most important design patterns you must know are
1) MVC (Model View Controller)
2) Target Action
3) Delegation
4) Blocks

1) MVC (Model View Controller)
In this pattern, model keep track of your app’s data, views display your user interface and make up the content of an app, and controllers manage your views. 
In an iOS app, your Interface builder(.xib) files are views, your interface(.h) and implementation(.m) file is a Controller and your database (CoreData or SQLite or SQL Server) is nothing as a Model.

This pattern separates the data objects in the model from the views used to present that data. This separation promotes code reuse by making it possible to swap out your views as needed and is especially useful when creating universal apps—that is, apps that can run on both iPad and iPhone.

2) Target Action
Target-action is a conceptually simple design in which one object sends a message to another object when a specific event occurs.

Consider an UIButton in a view say Login button on a UIView, on TouchUpInside event you are calling a selector method where you actually perform login action, here the Target is generally self or whichever the controller(XYZViewController) is handling the action and Action is Login in this example.

3) Delegation
Delegation is a simple and powerful pattern in which one object in an app acts on behalf of, or in coordination with, another object. 

The delegate of a framework class is automatically registered as an observer of notifications posted by the delegating object.The delegate need only implement a notification method declared by the framework class to receive a particular notification message.

Consider UITableView class where didSelectRowAtIndexPath: is a delegate method of UITableView,
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
This method tells the delegate that the specified row is now selected. The delegate handles selections in this method

Attribute tableView: A table-view object informing the delegate about the new row selection.

Attribute indexPath:An index path locating the new selected row in tableView.

By the help of this delegate method of UITableView, you will come to know which row of your table user has selected if your table is adopting and confirming to UITableView protocol, i.e; <UITableViewDelegate> in your interface(.h) file and yourTableViewObj.delegate = self; in your implementation(.m) file.

Advantage of this delegate method is No pain for a programmer to get the user selected row index.

4) Blocks
Blocks are a language-level feature, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects, which means they can be added to collections like NSArray or NSDictionary. They also have the ability to capture values from the enclosing scope,

The syntax to define a block literal uses the caret symbol (^), like this:
NSLog(@”This is a block”);
In the above example, the block doesn’t return any value, and doesn’t take any arguments.

2) use the operator to declare a block variable and to indicate the beginning of a block literal. The body of the block itself is contained within {}, as shown in this example
int multiplier = 4;
int (^myBlock)(int) = ^(int num) {
    return num * multiplier;

the block is able to make use of variables from the same scope in which it was defined.
In the above example myBlock is a block name, which returns an integer type, it takes an single argument of type int, num is an argument name and stuffs inside flower braces’{}’ is the body of the block and a block always ends with a semicolon(;).
- A block is commonly used in place of a call back function.
- It saves you having to create your own threads and maintain the state of each thread, manage locks & etc.
- Blocks can be used by multiple threads.

In addition to the above mentioned design patterns iOS is having even more design patterns like Abstract Factory,Adapter,Chain of Responsibility,Command,Composite,Decorator,Facade,Iterator,Mediator,Memento,Observer,Proxy,Receptionist,Singleton to know about these additional design patterns you can go through this Apples Official documentation

Hope this post was helpful, any comments or suggestions is acceptable.

Thursday, November 14, 2013

Subclass, Category and Extensions in Objective C

Today lets see what is subclassing, categories and extensions in Objective C, and where, when and how to use these concepts.

Note: A complete working Xcode project copy is available for download, which includes all the required examples to understand these concepts practically at the end of this post.

1) Subclass in Objective C

Subclassing in simple words is changing the behavior of properties or methods of an existing class or in other words subclassing is inheriting a class and modifying the methods or properties of super class however you want.

Suppose for example consider a UITextField class, by default the placeholder text of UITextField will be of light gray color with default system font. If we want to change this style just subclass UITextField and override drawPlaceholderInRect method.

Create a class of type UITextField and name it some thing like CustomUITextFieldPlaceholderAppearance

#import <UIKit/UIKit.h>
@interface CustomUITextFieldPlaceholderAppearance : UITextField

#import "CustomUITextFieldPlaceholderAppearance.h"

@implementation CustomUITextFieldPlaceholderAppearance
// override drawPlaceholderInRect method
- (void)drawPlaceholderInRect:(CGRect)rect {
    // Set color and font size and style of placeholder text
    [[UIColor redColor] setFill]; //set placeholder text color to red
    [[self placeholder] drawInRect:rect withFont:[UIFont fontWithName:@"verdana" size:14.0]]; //set custom font style and size to placeholder text 

Now in your application wherever you want this custom look and feel for placeholder text of textfield you can just import this subclass header file (#import "CustomUITextFieldPlaceholderAppearance.h") and create an object of this class and you are done. In addition to this look and feel the default delegate methods and properties of UITextField will remain same.

2) Categories in Objective C

An Objective C category allows you add your own methods to an existing class.

Categories are also called as "informal protocols".

Suppose take an example, since Foundation Framework classes such as NSString, NSArray, NSDate etc… doesn’t have any access to modify, you can add your own methods in to these classes by the help of a category.

Consider NSString Class and if suppose we want to add a reverse string method to NSString class, so that in our application at any point of time any NSString object can call this category method and get a reversed string as a result. We can do this as below,

Note: Usually naming convention for category file is like OriginalClassName+CategoryName

Lets create a category class with a name something like NSString+NSString_ReverseString

#import <Foundation/Foundation.h>

@interface NSString (NSString_ReverseString)
- (NSString *)reverseString:(NSString *)yourString;

#import "NSString+NSString_ReverseString.h"

@implementation NSString (NSString_ReverseString)

- (NSString *)reverseString:(NSString *)yourString
    NSMutableString *reversedStr = [NSMutableString stringWithCapacity:[yourString length]];
    [yourString enumerateSubstringsInRange:NSMakeRange(0,[yourString length])
                                 options:(NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences)
                              usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                  [reversedStr appendString:substring];
    return reversedStr;

Now in your application wherever you want  to reverse a string then just import this category header file (#import "NSString+NSString_ReverseString.h"
) and call our reverseString: method from any of NSString object and it will reverse and return you the reversed string.

In the above example we have added a custom method called reverseString: to NSString class from the help of a category.

Note that in a category you can’t add an instance variable, since methods within a category are added to a class at runtime.

3) Extensions in Objective C

Extensions are similar to categories but the need of extension is different.
- Class extensions are often used to extend the public interface with additional private methods or properties for use within the implementation of the class.
- Extensions can only be added to a class for which you have the source code at compile time (the class is compiled at the same time as the class extension).
- Extensions will be local to a class file.

The syntax to declare class extension looks like,
@interface ClassName()

since no name is given in the parentheses, class extensions are often referred to as anonymous categories.

Note Extensions can add instance variables.
@interface ABCExtension()
@property NSObject *yourProperty;

the compiler will automatically synthesize the relevant accessor methods, as well as an instance variable, inside the primary class implementation.
If you add any methods in a class extension, these must be implemented in the primary implementation for the class.

In any of your class in implementation file(.m), say ViewController.m
@interface ViewController ()
-(void)printName:(NSString *)name;

@implementation ViewController
-(void)printName:(NSString *)name

In the above extension example printName: method is private to class ViewController,  and cannot be accessed from outside the ViewController class.(even if you inherit since printName: is a private method their will not be any access to this method outside the class)

You can call this extension method only inside ViewController class, as below
[self printName:@"MyName"];

Usually people will use extensions to hide private information of a class without exposing them to access from any other class.

Finally few simple points to remember is 
- Subclassing is better option if you want to customize an existing stuffs or functionalities, and
- Category is a best option if you want to add additional functionalities to an existing class

You can download a Sample Xcode Project here.

Hope this post was helpful, any comments or suggestions is acceptable.

Wednesday, November 6, 2013

How to fix iOS 7 Status bar overlapping issue and status bar style

Hi folks, today lets see how to fix iOS 7 Status bar overlapping issue and making status bar style compatible in both iOS 6 and iOS 7 or in other words migrating your Xcode 4.x project to Xcode 5.x

      1)   Fixing Status Bar Overlapping issue in iOS 7.
      2)   Making Status Bar text visible in dark background.

1) Fixing Status Bar Overlapping issue in iOS 7 :

In iOS 7 status bar is transparent, and when you run your iOS project from Xcode 5 by selecting iOS 7, 4 inch retina device then your status bar will overlap your navigation bar, something like below,

To fix this issue one approach is as below,
a)  Select your interface builder(.xib) file in Xcode5 and
-                  Select file inspector tab and uncheck “use AutoLayout” checkbox.

b) Move all your UI Elements (views, buttons, imageviews etc) 20 pixels down.

c) Since we have moved all UI Elements to 20pixels down in iOS 6.0 there will be a 20 pixel gap on top of each UI Element so as to fix this, we have an new property in Xcode 5 interface builder called iOS 6/7 deltas.
- Go to Size Inspector tab and change Delta Y value to -20(so that it will work properly in all the iOS versions).

and that’s all status bar overlapping issue fixed.

Now if we run our app then the output is as below,

Status bar is not overlapping my navigation bar now but since my view is having a black or dark background and in iOS 7 status bar is transparent so that my status bar text is not visible at all.

To fix this there are couple of ways one simple approach is,

 2) Making Status Bar text visible in dark background :

      a) Go to info.plist file of your app.
      b) Add a ViewControllerBasedStatusBarAppearance Boolean key if it is not existing and assign value “NO”.
      c) Add “Status bar style” key if it is not existing and select “Opaque black style” value to it.

and that’s all we are done.
Now if i run my app the output is as below,

For complete reference here is a link for Apple's Documentation

Hope this post was helpful, any comments or suggestions is acceptable.