How will you create a static library in iOS?

What is a Static library?

A static library or statically-linked library is a set of routines, external functions and variables which are resolved in a caller at compile-time and copied into a target application by a compiler, linker, or binder, producing an object file and a stand-alone executable. This executable and the process of compiling it are both known as a static build of the program. Historically, libraries could only be static.

Why should we use Static Libraries?

1. Distribution
2. Reusability.

How to create a library Project in iOS?

Static libraries in iOS has a “.a” extension. So we are going to create it.

1. Open XCode and start a new project.
2. Under iOS, select Library and “Cocoa Touch Static Library”.

This will create a nice new project for us that builds a .a file.

Lets name it “SampleStaticLibrary”, This will create a library with name “SampleStaticLibrary.a”.
Although we can change it anytime.

Now we will get a SampleStaticLibrary.h and SampleStaticLibrary.m file.

Open the SampleStaticLibrary.h file and write some function prototypes in it.

 #import <Foundation/Foundation.h>

@interface SampleStaticLibrary : NSObject

- (void) functionOne
- (void) functionTwo;


Implement the same in SampleStaticLibrary.m file.

#import "SampleStaticLibrary.h"

@implementation SampleStaticLibrary

- (void) functionOne{
   NSLog("I am in functionOne");

- (void) functionTwo{
   NSLog("I am in functionTwo");


Important : Now connect your device or “Select iOS Device” for build. Remember when you hit run, its not going to run the application
since it is a library project. Xcode will just build the project.

Now go to the Products folder in the navigator and there you can see the library file with “.a” extension.

OOOOOhhh. Now we have built a Static Library in iOS. Right click on that file and click “Show in Finder”. There you will get the
library file or you can just drag and drop the file, make sure you click “copy file in the dialog” while importing.

Important : while importing to another project, you have to include the “.h” files that were present in your library project too in your Working project. So make sure you copy all “.h” files too.

Hooray..You have built a static library in iOS. Now we are gonna use it.

//You can do this in the "ViewController.h" file.

#import "SampleStaticLibrary.h"

@interface ViewController ()


@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    SampleStaticLibrary *s = [[SampleStaticLibrary alloc] init];
    [s functionOne];



Go on and run your project.

Please leave your valuable comments below this post.

Simple Core Data tutorial in iOS

In this tutorial we will be making a simple application to save a person details using Core Data.

Here we will have two models or it can be said as Database tables – Model1 and Model2.

Below are the basic things about Core Data…

Core Data Stack

The key objects of the stack are the
1. managed object model,
2. the persistent store coordinator,
3. and one or more managed object contexts.

NSManagedObjectModel – compare the managed object model to the schema of a database, that is, it contains information about the models or entities of the object graph, what attributes they have, and how they relate to one another.

NSPersistentStoreCoordinator – NSPersistentStoreCoordinator object persists data to disk and ensures the persistent store(s) and the data model are compatible. It mediates between the persistent store(s) and the managed object context(s) and also takes care of loading and caching data.
Core Data has caching built in.

NSManagedObjectContext – The NSManagedObjectContext object manages a collection of model objects, instances of the NSManagedObject class.

Create a new project with the “Use CoreData” Checkbox checked in…

So your app delegate should have the following methods

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.coderzheaven.CoreDataDemo" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreDataDemo" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    // Create the coordinator and store
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataDemo.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    return _persistentStoreCoordinator;

- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

In the Project Navigator on the left, you should see a file named Core_Data.xcdatamodeld. This is the data model of the application that’s compiled to a .momd file. It’s that .momd file that the managed object model uses to create the application’s data model.

Now we will create two models or Tables to work with.
Click on the CoreDataModel file in the navigator and you will see a window like the one below.

You can click on the “Add Entity” Button on the bottom to create new Models.

Here I have created two models – Model1 and Model2.
Model1 has name, place and a relation to the Model2.
Model2 has age and profession.
You can click on “Create Attribute” to create new member variables inside the Model.

Core Data Demo iOS

For saving the data you can use the Following code.

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    NSManagedObject *personInfo = [NSEntityDescription
    [personInfo forKey:@"name"];
    [personInfo forKey:@"place"];
    NSManagedObject *otherInfo = [NSEntityDescription
    [otherInfo setValue:@"25" forKey:@"age"];
    [otherInfo setValue:@"Engineer" forKey:@"profession"];
    [personInfo setValue:otherInfo forKey:@"model2"];
    NSError *error;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);

For retrieving the data , use the below code.

 AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    NSError *error;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"Model1" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    NSMutableString *allData = [NSMutableString new];
    for (NSManagedObject *info in fetchedObjects) {
        NSManagedObject *details = [info valueForKey:@"model2"];
        NSLog(@"Name: %@", [info valueForKey:@"name"]);
        NSLog(@"Place: %@", [info valueForKey:@"place"]);
        NSLog(@"Age: %@", [details valueForKey:@"age"]);
        [allData appendFormat:@"Name : %@\n", [info valueForKey:@"name"]];
        [allData appendFormat:@"Place : %@\n", [info valueForKey:@"place"]];
        [allData appendFormat:@"Age : %@\n", [details valueForKey:@"age"]];
        [allData appendFormat:@"Profession : %@\n", [details valueForKey:@"profession"]];

You can download the complete source code from here.

Create a date in your format in IOS

Below functions takes the current date and time and formats it to give a date-time string.
You can customise it in the way you want.

The string that the below function generates will be like this – 23-Dec-2014 4:23 PM

//Get the current date...
+(NSDate *) getCurrentDate
    NSDate *now = [NSDate date];
    return now;

//Get the date and time in a formatted way...
+(NSString *) getFormattedDateAndTime
    NSDate *now = [Global getCurrentDate];
    int hour;
    NSString *am_pm;
    //Get calendar Instance
    NSCalendar *cal=[NSCalendar currentCalendar];

    //optionally set the Locale
    //NSTimeZone *tz=[NSTimeZone timeZoneWithName:@"America/Chicago"];
    //[cal setTimeZone:tz];

    NSDateComponents *comp=[cal components:NSCalendarUnitHour|NSCalendarUnitMinute fromDate:now];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MMM-yyyy"];
    NSString *stringFromDate = [formatter stringFromDate:now];

    hour = (int)[comp hour];
    am_pm = (hour >= 12) ? @"PM" : @"AM";
    if(hour >= 12){
        hour = hour - 12;
    // 23-Dec-2014 4:23 PM
    NSString *dateTimeStr = [NSString stringWithFormat:@"%@ %d %d %@", 
                            stringFromDate, (int)hour, (int)[comp minute], am_pm];
    return dateTimeStr;

Use “MMMM” for “December” and “MMM” for “Dec” in month.

What is @property in iOS mean?

The goal of @property directive in iOS is to create the getters and setters for that object so that you can access it in your program. It allows you to specify the behavior of a public property on a semantic level, and it takes care of the implementation details for you.

This article also tells how you can alter these “getters and setters” that are generated by @property

The @property Directive

Let’s see what happens when we declare an @property directive.

Lets study it with an example

 // Car.h
#import <Foundation/Foundation.h>

@interface Car : NSObject

@property BOOL running;

// Car.m
#import "Car.h"

@implementation Car

@synthesize running = _running;    // Optional for Xcode 4.4+


The compiler generates a getter and a setter for the “running” property.
The default naming convention is to use the property itself as the getter, prefix it with set for the setter, and prefix it with an underscore for the instance variable, like so:

- (BOOL)running {
    return _running;
- (void)setRunning:(BOOL)newValue {
    _running = newValue;

So when you declare a variable using @property this means that you can call its getter and setter as if it is included in the class interface.

You can also override them in Car.m to supply custom getter/setters, but this makes the @synthesize directive mandatory.
However, you should rarely need custom accessors, since @property attributes let you do this on an abstract level.

so when you call

Car *maruti = [Car new];
maruti.running = YES;                // [maruti setRunning:YES]
NSLog(@"%d", maruti.running);        // [maruti running]

You can also change the default getter and setter like this.

@property (getter=isRunning) BOOL running;

Now the “getter” method is called “isRunning” and “setter” method is “setRunning”

Car *maruti = [[Car alloc] init];
maruti.running = YES;                // [maruti setRunning:YES]
NSLog(@"%d", maruti.running);        // [maruti isRunning]
NSLog(@"%d", [maruti running]);      // Error: method no longer exists

The readonly Attribute

When you specify “readonly” attribute to a variable, compiler omits its its setter method but the “getter” is unaffected.

#import <Foundation/Foundation.h>

@interface Car : NSObject

@property (getter=isRunning, readonly) BOOL running;

- (void)startEngine;
- (void)stopEngine;


// Car.m
#import "Car.h"

@implementation Car

- (void)startEngine {
    _running = YES;
- (void)stopEngine {
    _running = NO;


@property also generates an instance variable for us, which is why we can access _running without declaring it anywhere (we can’t use self.running here because the property is read-only).

Car *maruti = [Car new];
[maruti startEngine];
NSLog(@"Running: %d", maruti.running);
maruti.running = NO;                      // Error: read-only property

The nonatomic Attribute

Atomicity deals with how properties behave in a threaded environment.
When you have more than one thread, it’s possible for the setter and the getter to be called at the same time.
This means that the getter/setter can be interrupted by another operation, possibly resulting in corrupted data.

Using atomic somewhat means that your variable is thread safe.

Properties declared with @property are atomic by default, and this does incur some overhead.

So if we can do like this if you application is not a multithreaded application

@property (nonatomic) NSString *model;

The strong Attribute

The strong attribute creates an owning relationship to whatever object is assigned to the property. This is the implicit behavior for all object properties, which is a safe default because it makes sure the value exists as long as it’s assigned to the property.

Let’s take a look at how this works by creating another class called Person. It’s interface just declares a name property:

// Person.h
#import <Foundation/Foundation.h>

@interface Person : NSObject

@property (nonatomic) NSString *name;


// Person.m
#import "Person.h"

@implementation Person

- (NSString *)description {


Above implementation overrides NSObject’s description method, which returns the string representation of the object.

Now we will add a person to the Car Class

// Car.h
#import <Foundation/Foundation.h>
#import "Person.h"

@interface Car : NSObject

@property (nonatomic) NSString *model;
@property (nonatomic, strong) Person *driver;


Now during usage

Person *hari = [Person new]; = @"hari";

Car *maruti = [Car new];
maruti.model = @"Maruti Swift";
maruti.driver = hari;

NSLog(@"%@ is driving the %@", maruti.driver, maruti.model);

Since driver is a strong relationship, the maruti object takes ownership of john.
This ensures that it will be valid as long as maruti needs it.

The weak Attribute

Strong references pose a problem if, for example, we need a reference from driver back to the Car object he’s driving. First, let’s add a car property to Person.h:

// Person.h
#import <Foundation/Foundation.h>

@class Car;

@interface Person : NSObject

@property (nonatomic) NSString *name;
@property (nonatomic, strong) Car *car;


The @class Car line is a forward declaration of the Car class. It’s like telling the compiler, “The Car class exists, don’t try to find it right now.”

Now use it like this

maruti.driver = hari; = maruti;       // Add this line

Now there is a relation b/w maruti and Person and also Person and maruti.
So it is not destroyable by memory management.

This is called a retain cycle, which is a form of memory leak.

But we can fix it by using “weak” attribute like this

@property (nonatomic, weak) Car *car;

The weak attribute creates a non-owning relationship to car.
This allows hari to have a reference to maruti while avoiding a retain cycle.

The copy Attribute

The copy attribute is an alternative to strong. Instead of taking ownership of the existing object, it creates a copy of whatever you assign to the property, then takes ownership of that. Only objects that conform to the NSCopying protocol can use this attribute.


// Car.h
@property (nonatomic, copy) NSString *model;

Now, Car will store a brand new instance of whatever value we assign to model.

Car *maruti = [Car new];
NSMutableString *model = [NSMutableString stringWithString:@"Maruti Swift"];
maruti.model = model;

NSLog(@"%@", maruti.model);
[model setString:@"Maruti Zen"];
NSLog(@"%@", maruti.model);            // Still "Maruti Swift"

The retain Attribute

The retain attribute is the Manual Retain Release version of strong, and it has the exact same effect: claiming ownership of assigned values.
You shouldn’t use this in an Automatic Reference Counted environment.

The assign Attribute

The assign attribute doesn’t perform any kind of memory-management call when assigning a new value to the property.
This is the default behavior for primitive data types, and it used to be a way to implement weak references before iOS 5.
Like retain, you shouldn’t ever need to explicitly use this in modern applications.


getter= —> Use a custom name for the getter method.
setter= —> Use a custom name for the setter method.
readonly —> Don’t synthesize a setter method, creates only getter method [the trick to make setter method “private” for class users – so only getter method will be visible for compiler. Usually in implementation file this property is redeclared without readonly attribute using custom category so that setter method can be used inside class itself.]
nonatomic —> Don’t guarantee the integrity of accessors in a multi-threaded environment. This is more efficient than the default atomic behavior.
strong —> Create an owning relationship between the property and the assigned value. This is the default for object properties. [synthesized getter method will return ivar directly without locking it for thread-safety]
weak —> Create a non-owning relationship between the property and the assigned value. Use this to prevent retain cycles.
copy —> Create a copy of the assigned value instead of referencing the existing instance.
retain —> Class retains the pointer, the previous value is released

Creating a Custom Alert or PopUp in iOS

Custom PopUp IOS

First we will write a class that extends UIView to create a Custom PopUp

Create a Cocoa file and name it CustomPopUp

You should get two files CustomPopUp.h and CustomPopUp.m


#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@protocol ClickDelegates;

@interface CustomPopUp : UIView{
      UIView *childPopUp;
      id<ClickDelegates> _click_delegate;
      UIViewController *_parent;

@property (nonatomic, retain) id<ClickDelegates> _click_delegate;
@property (nonatomic, retain) UIViewController *_parent;

-(void) initAlertwithParent : (UIViewController *) parent withDelegate : (id<ClickDelegates>) theDelegate;

-(IBAction)OnOKClick :(id) sender;

-(void) hide;

-(void) show;


// Delegate

@protocol ClickDelegates<NSObject>


-(void) okClicked;
-(void) cancelClicked;



#import "CustomPopUp.h"
#import "Util.h"

@implementation CustomPopUp{
    float popUpX;
    CGRect popUpRect;

@synthesize _click_delegate, _parent;

-(void) initAlertwithParent : (UIViewController *) parent withDelegate : (id<ClickDelegates>) theDelegate{
    self._click_delegate = theDelegate;
    self._parent = parent;
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    CGFloat screenHeight = screenRect.size.height;
    CGRect rect = CGRectMake(0, 0, screenWidth, screenHeight);
    self.frame = rect;
    self.backgroundColor = [UIColor clearColor];
    childPopUp = [UIView new];
    float popUpHeight = screenHeight/3;
    popUpX = 20.0;
    popUpRect = CGRectMake(popUpX, (screenHeight - popUpHeight)/2, screenWidth - (popUpX * 2), popUpHeight); =;
    self.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.001, 0.001);
    [self setBorderOnly:childPopUp withBGColor:[UIColor orangeColor] withCornerRadius:5.0 andBorderWidth:0.0 andBorderColor:[UIColor greenColor] WithAlpha:1];
    childPopUp.frame = popUpRect;
    [self addSubview:childPopUp];
    [self addLabel];
    [self addButton];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(bounce1AnimationStopped)];
    self.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.1, 1.1);
    [UIView commitAnimations];

-(void) show{

    [self._parent.view addSubview:self];

-(void) addLabel{
    // Add Label
    UILabel *lblForDisplay=[[UILabel alloc]initWithFrame:CGRectMake(popUpX, popUpX, popUpRect.size.width - popUpX, popUpX)];
    lblForDisplay.backgroundColor=[UIColor clearColor];
    lblForDisplay.textColor=[UIColor blackColor];
    lblForDisplay.text=@"This is a custom Alert";
    [childPopUp addSubview:lblForDisplay];

-(void) addButton{
    // Add Button
    UIButton *okBtn = [[UIButton alloc]initWithFrame:CGRectMake(popUpX, childPopUp.frame.size.height - 50, popUpRect.size.width - 40, 40)];
    okBtn.backgroundColor=[UIColor blueColor];
    [self setBorderOnly:okBtn  withBGColor:[UIColor greenColor] withCornerRadius:5.0 andBorderWidth:0.0 andBorderColor:[UIColor greenColor] WithAlpha:1];
    [okBtn setTitle:@"OK" forState:UIControlStateNormal];
    [okBtn addTarget:self action:@selector(OnOKClick:) forControlEvents:UIControlEventTouchDown];
    [childPopUp addSubview:okBtn];

-(IBAction)OnOKClick :(id) sender{
    [_click_delegate okClicked];

-(void) show : (UIViewController *) parent{

-(void) hide{
    [self removeFromSuperview];

- (void)bounce1AnimationStopped {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:.2];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(bounce2AnimationStopped)];
    self.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.9, 0.9);
    [UIView commitAnimations];

- (void)bounce2AnimationStopped {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:.2];
    self.transform = CGAffineTransformIdentity;
    [UIView commitAnimations];

-(void) setBorderOnly:(UIView *) theView withBGColor:(UIColor *) color withCornerRadius :(float) radius andBorderWidth :(float) borderWidth andBorderColor :(UIColor *) bgColor WithAlpha:(float) curAlpha
    theView.layer.borderWidth = borderWidth;
    theView.layer.cornerRadius = radius;
    theView.layer.borderColor = [color CGColor];
    UIColor *c = [color colorWithAlphaComponent:curAlpha];
    theView.layer.backgroundColor = 1;


I have a sample interface like this.

Custom PopUp IOS

Now the ViewController.m

#import "ViewController.h"

@interface ViewController ()


@implementation ViewController{

    CustomPopUp *mPopUp;

- (void)viewDidLoad {
    [super viewDidLoad];
    //create delegate    
    mPopUp = [CustomPopUp new];
    [mPopUp initAlertwithParent:self withDelegate:self];

-(void) okClicked{

    [mPopUp hide];

-(void) cancelClicked{

-(IBAction)showAlert :(id)sender{
    [mPopUp show];

-(IBAction)dummyClick :(id)sender{
    NSLog(@"Click Dummy");

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];



You can download the complete source code from here.

StoryBoards in iOS – A Simple Example

Hey everyone,

Today we will see how we can use storyboards in an application.

First we will Create a sample project named “StoryBoardDemo”

StoryBoards in iOS, iPhone ,iPad, Apple

StoryBoards in iOS, iPhone ,iPad, Apple

Now we will Add the Navigation Controller
For that Go To Menu -> Editor >Embed In -> NavigationController

StoryBoards in iOS, iPhone ,iPad, Apple

StoryBoards in iOS, iPhone ,iPad, Apple

Now Double Click on the Title Bar and Add the title “Companies”

StoryBoards in iOS, iPhone ,iPad, Apple

Now Drag a table View on to the ViewController.
StoryBoards in iOS, iPhone ,iPad, Apple

Now we will add a prototype cell (a row) in the TableView

Search and Drag a “TableView Cell” inside the TableView.

StoryBoards in iOS, iPhone ,iPad, Apple

Now Select the TableView Prototype Cell and Go to the Attributes Inspector.

Select “Style = Basic”
Identifier = “Company_cell” // This is for referencing each row inside the code.

Now a new Label will appear inside the Prototype Cell.

StoryBoards in iOS, iPhone ,iPad, Apple

Make sure you link “delegate” and “datasource” to the view controller.
Otherwise data will not appear in the tableview.
For that Control Click on the tableView and Drag to the ViewController in the TreeView on
the left.

OK Now we will add another ViewController and add a connection between ViewControllers.

Right Click on the Project Name -> Add New Files > Cocoa touch
[Please UNTICK the checkbox to create the XIB file]

I said to UNTICK the creation of XIB file because we are here to study How STORYBOARD works right?

StoryBoards in iOS, iPhone ,iPad, Apple

So we will add new controller to the storyboard as follows.
Click on the Main.StoryBoard. Go to the Controls section and Search for ViewController and Drag to the storyboard and add a label to it.
You may customise the label you want.

StoryBoards in iOS, iPhone ,iPad, Apple

StoryBoards in iOS, iPhone ,iPad, Apple

Now Do exactly the same step.

Ctrl + Click on the TableView Row(prototype Cell) in the Companies-List ViewController and Drag to DetailsViewController.

Now a window will popup , From that under the “Select Sugue” section click “show”.
Here what we have done is we are telling the controller that when we click on the Tableview Row it should navigate to DetailView Controller.

Next Step Ctrl Click on the Bridge between the ComapniesViewController and DetailViewController, then Go to the attributes inspector on the right.
Give a name for the bridge.

StoryBoards in iOS, iPhone ,iPad, Apple

Now we will go to code


Add the tableview delegates, so that we can get the event on the click of the tableview.

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) IBOutlet UITableView *_tableView;



#import "CompaniesViewController.h"
#import "DetailsViewController.h"

@interface ViewController ()


@implementation ViewController{
    NSArray *_companies;

@synthesize _tableView;

- (void)viewDidLoad {
    [super viewDidLoad];
      _companies = [NSArray arrayWithObjects:@"Apple", @"Google", @"Sony", @"Samsung", @"HTC", nil];

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    return [_companies count];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    static NSString *simpleTableIdentifier = @"RecipeCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    cell.textLabel.text = [_companies objectAtIndex:indexPath.row];
    return cell;


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"ShowCompanyDetail"]) {  // This should be the same id as the bridge between controllers.
        NSIndexPath *indexPath = [self._tableView indexPathForSelectedRow];
        DetailsViewController *destViewController = segue.destinationViewController;
        destViewController._companyName = [_companies objectAtIndex:indexPath.row];

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];


In the DetailsViewController we will add two variables
one for the Label holding the value and the value itself

Make sure you link the label to the variable


#import <UIKit/UIKit.h>

@interface DetailsViewController : UIViewController

@property (nonatomic, strong) IBOutlet UILabel *_companyLabel;
@property (nonatomic, strong) NSString *_companyName;



#import "DetailsViewController.h"

@interface DetailsViewController ()


@implementation DetailsViewController

@synthesize _companyLabel;
@synthesize _companyName;

- (void)viewDidLoad {
    [super viewDidLoad];
    // we set the value passed from the companies view controller to the label
// in the Detailview controller.
    _companyLabel.text = _companyName;

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.

You can download the complete source code from here.

Localhost for Android Emulator and iPhone Simulator.

If you are trying to access a file (PHP or java) residing in your server in your own machine, then
you have to use a specific IP to access it. If it is public, then use the other System’s IP

1. If it is localhost, In Android you use it as

The localhost refers to the device on which the code is running, in this case the emulator.

If you want to refer to the computer which is running the Android simulator, use the IP address instead. You can read more from here.

2. If you are trying to access from iOS Simulator use can use


The iOS Simulator uses the host machine network so you should be able to just use localhost or your machines IP address, whichever IP your web service is listening on.

Handling Files in iOS

Hi All,

In Todays article we will see how we can handle files in Objective C.

The list of the methods used for accessing and manipulating files are listed below. Here you have to replace the FilePath1, FilePath2 and FilePath strings to our required full file paths to get the desired action.

NSFileManager *fileManager = [NSFileManager defaultManager];
 //Get documents directory
 NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
 (NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
 if ([fileManager fileExistsAtPath:@""]==YES) {
           NSLog(@"File exists");

Comparing two file contents

 if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) {
         NSLog(@"Same content");

Check if writable, readable and executable

 if ([fileManager isWritableFileAtPath:@"FilePath"]) {
         NSLog(@"File isWritable");

  if ([fileManager isReadableFileAtPath:@"FilePath"]) {
          NSLog(@"File isReadable");

 if ( [fileManager isExecutableFileAtPath:@"FilePath"]){
          NSLog(@"File is Executable");

Move file

 if([fileManager moveItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]){
          NSLog(@"File Moved successfully");

Copy file

if ([fileManager copyItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]) {
          NSLog(@"File Copied successfully");

Remove file

 if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) {
          NSLog(@"File Removed successfully");

Read file

 NSData *data = [fileManager contentsAtPath:@"Path"];

Write file

 [fileManager createFileAtPath:@"" contents:data attributes:nil];

Delegates in iOS – A Simple Example

Hi All,

Today I am going to talk about iOS Delagates.
This example shows how to write a common delegate for a mail composer in iOS.

First I am going to crate a seperate class for invoking the MailComposer Modal view controller.
The class is named “Common”.

So Create .m and .h files for Common.


#import <Foundation/Foundation.h>
#import <MessageUI/MessageUI.h>

@interface Common : NSObject{
    MFMailComposeViewController *mailComposer;

@property (nonatomic, weak) id <MFMailComposeViewControllerDelegate> delegate;

-(void)sendMail:(UIViewController *) cont : (NSString *) mailSubject : (NSString *) mailBody;

-(void) setDelegate:(id <MFMailComposeViewControllerDelegate>)aDelegate;


Now Go to Common.m and implement the methods.

#import "Common.h"

@implementation Common

@synthesize delegate;

-(void)sendMail:(UIViewController *) cont :(NSString *) mailSubject : (NSString *) mailBody{
    mailComposer = [[MFMailComposeViewController alloc]init];
    [mailComposer setSubject:mailSubject];
    mailComposer.mailComposeDelegate = delegate;
    [mailComposer setMessageBody:mailBody isHTML:NO];
    [cont presentViewController:mailComposer animated:YES completion:nil];

-(void) setDelegate:(id <MFMailComposeViewControllerDelegate>)aDelegate{
    if (delegate != aDelegate) {
        delegate = aDelegate;        


Now Go to ViewController.h

We don’t need any declarations inside this class, just need to add the delegate

#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>

@interface ViewController : UIViewController<MFMailComposeViewControllerDelegate>

Now in the implementation class


#import "ViewController.h"
#import "Common.h"

@interface ViewController ()


@implementation ViewController

- (void)viewDidLoad

    Common *com = [Common new];
    [com setDelegate:self];   // Setting the Mail Composer delegate
    [com sendMail:self :@"Mail Subject" :@"Mail Body"];

#pragma mark - mail compose delegate
-(void)mailComposeController:(MFMailComposeViewController *)controller
         didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
    if (result) {
        NSLog(@"Result : %d",result);
    if (error) {
        NSLog(@"Error : %@",error);
    [self dismissViewControllerAnimated:YES completion:nil];

Ok. Now our MailComposer Delegate is implemented. Go on and run the application.

How to add info button to right side or leftside of navigationbar in iPhone?

    UIButton* infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
    [infoButton addTarget:self action:@selector(showInfoView:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton];

Adding button action function.

- (IBAction)showInfoView:(id)sender {

Random Integer array without repetition in Objective C Iphone

This sample code generates a random number and checks whether its already present in the array.
If yes then it will not add else it will add, thus generating a random array without duplicates.

-(NSMutableArray *) generateRandomArray : (int) max{
    NSMutableArray *randArray = [NSMutableArray new];
    for (int k = 0; k < max; k++) {
       int r = arc4random() % max;
        if([randArray containsObject:[NSString stringWithFormat:@"%d", r]]){
            [randArray addObject:[NSString stringWithFormat:@"%d", r]];
    NSLog(@"RAND %@",randArray);
    return randArray;

Please leave your valuable comments if you found this post useful.

How to download an image from a URL in Objective C iPhone?

Download image from URL in iPhone

This method downloads the image from the specified URL and stores in the documents directory and then shown in an ImageView.
Make sure you have an imageview linked with the outlet in the UserInterface.

-(void) downloadImageFromURL :(NSString *)imageUrl{
    NSURL  *url = [NSURL URLWithString:imageUrl];
    NSData *urlData = [NSData dataWithContentsOfURL:url];
    if ( urlData )
        NSLog(@"Downloading started...");
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"dwnld_image.png"];
        NSLog(@"FILE : %@",filePath);
        [urlData writeToFile:filePath atomically:YES];
        UIImage *image1=[UIImage imageWithContentsOfFile:filePath];

Please leave your comments if you found this code useful.

How to create a radioGroup in Android inside a Scrollview?

Here is a sample code that creates a radiobutton group inside a scrollview.
Please make sure you have a scrollview in your UI and its linked.

// This function adds the radio buttons inside the scrollview.
Here I am using some of my variables to generate the count of radio buttons.
Please make sure to change it before using it in your code.

UIRadioButton implementation in iPhone
UIRadioButton implementation in iPhone

NSString *const CHECKED_IMAGE = @"radiochecked.png";
NSString *const UNCHECKED_IMAGE = @"radiounchecked.png";

int y=0;
    for(int optionCount = 0; optionCount < [pracObj.answers count]; optionCount++){
        UIButton *answerCheckBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [answerCheckBtn addTarget:self action:@selector(answerSelected:)
        [answerCheckBtn setTitle:@"" forState:UIControlStateNormal];
        //set background image for button
        answerCheckBtn.backgroundColor = [UIColor clearColor];
        answerCheckBtn.frame = CGRectMake(1.0, y+2, 20,20);
        UIImage *buttonImageNormal = [UIImage imageNamed:UNCHECKED_IMAGE];
        UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
        [answerCheckBtn setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
        answerCheckBtn.tag = optionCount + ANSWERTAG_STARTING;
        UILabel *answerLabel = [UILabel new];
        answerLabel.tag =  optionCount+100;
        answerLabel.text = [[pracObj.answers objectAtIndex:optionCount] stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
        answerLabel.lineBreakMode = NSLineBreakByWordWrapping;
        answerLabel.numberOfLines = 1;       
        answerLabel.frame = CGRectMake(30, y+2, 300.0, 20.0);
        [answerLabel sizeToFit];
        [answerLabel setFont:[UIFont systemFontOfSize:10]];
        [answersScrollView addSubview:answerCheckBtn];
        [answersScrollView addSubview:answerLabel];

And click of each radio button you can cal this function to reset the image.

    UIButton *curBtn = (UIButton*) sender;
    NSLog(@"DYN MEthod Clckd %d", curBtn.tag);
    UIImage *buttonImageNormal = [UIImage imageNamed:CHECKED_IMAGE];
    UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
    [curBtn setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
    [self clearButtons:curBtn.tag];

-(void) clearButtons:(int) curTag
    int totalAnsCount = [curPracticeQuestionObj.answers count];
    for (int y = ANSWERTAG_STARTING; y < (ANSWERTAG_STARTING + totalAnsCount); y++) {
        if (y != curTag) {
            UIButton *otherButton = (UIButton *)[answersScrollView viewWithTag:y];
            UIImage *buttonImageNormal = [UIImage imageNamed:UNCHECKED_IMAGE];
            UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
            [otherButton setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];

How to split a string using a delimiter in iPhone and add it to a mutable array?

Here is a simple code that does this..

-(NSMutableArray *) getAnswers :(NSString *) yourstring{
    NSMutableArray *answers = [NSMutableArray new];
    NSArray *parts = [[yourstring componentsSeparatedByString:@","];
    for(NSString *str in parts){
        [answers addObject:str];
    NSLog(@"RET answers %@", answers);
    return answers;

After splitting the string with “componentsSeparatedByString” the parts are added to a NSMutableArray using addObject.

A 4.8 inch iPhone may be on the way

Every iPhone user may be envious on seeing a bigger screen Android Phone.

iPhone 5S

But don’t worry Apple is said to be working on an iPhone with a 4.8-inch screen, a 20% increase in screen size from the iPhone 5S, iPhone 5C and iPhone 5.

Jeffries analyst Peter Misek has issued a research note to investors where he cited supply chain sources in China claiming that Apple will unveil an iPhone with 4.8-inch screen. This model is scheduled to be launched in September next year and will be named iPhone 6, said Misek.

You can read more about the story from here

Apple iPhones may come up with as less as $99 in the future


these are the rumours about the future iphone. Apple is reportedly looking at iPhones with bigger screens and will be releasing the low cost phone in
a range of colors as soon as this year, the ABC News reports.

According to the report, Apple declined to comment on the rumors,
Cook also said the iPhone doesn’t have a larger screen right now for a few reasons.

He said that a large screen today comes with a lot of tradeoffs, adding that people do look at the size, but they also look at things like if the photos show the proper color, the white balance, reflectivity, battery life, brightness, the longevity of the display.

Read more from here

Google to unveil Moto X to take on Apple.


Google bought Motorola in 2011 and ever since there has not been a phone from Google and Motorola.
Now it is that Google will be unveiling Moto X to take on rival Apple.

iPhone overprice tag has not come down since its launch in 2007. This will be a area where Google and Motorola will be targeting.

While Apple’s critics say the once wildly inventive company is running out of ideas, Motorola’s chief executive, Dennis Woodside, has promised to bring “audaciousness” and “innovation” back to mobile computing.

In a future-gazing presentation at the AllThingsD conference in California, Woodside, who has been charged with turning around the company that invented the first mobile phones of the 1980s, said he was also working on wearable technology.

Read complete story from here.

Budget iPhone 5 Coming Soon

iPhone 5

The budget version of Apple’s latest iPhone will cost roughly $330 (£220), priced in order to appeal to young, middle class consumers in countries like China and India.
The claims about the price and the imminent release were made on the Japanese website Macotakara, following on from earlier reports about Apple plans for a cheaper phone.
In January it was reported that the planned new phone will resemble the iPhone 5 from the front but Apple will replace that handset’s aluminium body with a cheaper plastic casing.

Read More from here

iPhone Mini launch this summer

iPhone Mini

A low-priced iPhone makes a lot of sense, Morgan Stanley says, and it even could hit the market this summer.
Katy Huberty, an analyst with the banking firm, noted that after her meetings with Apple Chief Financial Officer Peter Oppenheimer, she’s convinced that innovation remains a top priority for the Cupertino, Calif., electronics giant. She also believes that Apple will increase cash return to shareholders and expand carriers, distribution, and possibly price points to drive iPhone growth.
She noted that a lower priced iPhone makes sense for several reasons:
“iPad Mini is expanding Apple’s customer base with 50 [percent] of purchases in China/Brazil representing new customers to the ecosystem.”
“Chinese consumers show a desire to purchase the latest version of iPhone (instead of discounted older generations).”
“iPhone 4 demand surprised to the upside in the December quarter.”

Read more from here

How to call a function in background in Xcode(iPhone)?

“performSelectorInBackground” will call anyfunction to execute in background and you can also pass string parameters with this method or if you want to pass more params then pass the parameters as an object.

[self performSelectorInBackground:@selector(myBackgroundMethod:) withObject:@”String Params”];

How to Change UIWebview’s background color in iPhone Xcode?

Unlike other UIViews, the UIWebview’s opaque property is set to true by default. That should be set to false for changing the background color.

[myWebView setOpaque:NO];

myWebView.backgroundColor=[UIColor redColor];

Apple fined by China court for copyright violation

A court in China has ordered Apple to pay compensation to eight Chinese writers and two companies for violating their copyrights.

They had claimed that unlicensed electronic versions of their books had been sold on Apple’s online store.

The court ordered Apple to pay them 1.03m yuan ($165,000; £100,000) in compensation, according to the official news agency Xinhua.
… Read more from here.

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (

2. Click on the Profile icon on the Left.

3. If you look at the URL in the address bar, it should look something like this:

4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:


Google + CoderzHeaven

Which you think is the best – Android or iPhone?

This is a question that has been here since 2007. We know there are many advantages for Android phones and Apple’s iPhone. So what you think, which one is the best.

I will say my personal opinion. And I think Android is the best.

Android vs iPhone

What is your opinion?

Are you an iPhone or ANDROID User?

Why you think one is better than the other from your personal experience?

Do you think Fragmentation is a curse for ANDROID or iPhone?

Paste you opinion here and Let’s see what real phone users are thinking.

New iPhone may be getting Larger screens.


The new iPhone that Apple Inc. is expected to unveil this year is likely to have a larger display than its current models have, with the company ordering bigger screens from its Asian suppliers, people familiar with the matter said.

The new screens measure at least 4 inches diagonally, the people said, compared with 3.5 inches on Apple’s latest model, the iPhone 4S. Production is set to begin next month, the people said. Analysts have predicted that the next iPhone will come out in the fall.

Read more from here..