Reader Level:
ARTICLE

Singleton Pattern in iPhone

Posted by Sachin Bhardwaj Articles | iOS December 14, 2012
In this article I will explain the Singleton Design Pattern with example.
  • 0
  • 0
  • 3010
Download Files:
 

Introduction

A singleton is a special kind of class where only one instance of the class exists for the current process. (In the case of an iPhone app, the one instance is shared across the entire app.) Or we can say a solution of the encapsulation problem is to create classes that manage any global data as discreet modules. This is done through a singleton.

It's an extremely powerful way to share data among various parts of code without having to pass the data around manually.

To better understand Singletons here we use an example.

In this article I will create a Single View application and use the UITableViewController class to save data in a table taken from the user. To add a table view controller class we use the followiing.

Select any one Objective-C class and right-click on it then choose new file -> select objective C class -> click on next -> Choose subclass UITableViewController from the drop down list and enter whatever class name you want. If you want to use xib then you mark on it -> click on next -> select the location where you import the view controller class in the project.

Here in the first UIView I use one button and one text field from outlet. It is a class which is used to get input from the user and show output in another view TableViewContoller.

Now we create a simple project to understand the Singleton Pattern.

Step 1

Open XCode by double-clicking on it.

Step 2

Create a New XCode Project by clicking on it.

Step 3

Now select a Single View Application and click on Next.

Step 4

Now provide your Product Name. Here I use TableView and Company Identifier Mcn Solutions and click on Next.

Step 5

Select the location where you want to save your project and click on Create.

Step 6 

Select ViewController.Xib class and right-click on it.

Choose New File..

Step 7

Select the Objective-C class.

Select-objective-c-class-in-iPhone.jpg
 

Step 8

Select Subclass of UITableViewController from the drop down list and provide it the name ExampleDataViewController and click on the checkbox with xib to use the interface.

 table-view-controller-class-in-iphone.jpg

Click on Next.

Step 9

As it is we add one more Objective-C Class NSObject type.

Step 10

Now To use the Singleton Pattern we use the following code:

Singleclass.h

 #import <Foundation/Foundation.h>

@interface Singletonclass : NSObject
{
NSMutableArray *array;
}
@property(strong,nonatomic)NSMutableArray *array;

+(Singletonclass*)sharedobject;
@end

Singleclass.m

#import "Singletonclass.h"

@implementation Singletonclass
 
@synthesize array;

static Singletonclass*  _sharedobject=nil;

+(Singletonclass *)sharedobject
{
    @synchronized([Singletonclass class])
    {
        if (!_sharedobject)
            _sharedobject=[[self alloc] init];
       
        return _sharedobject;
    }
   
    return nil;
}

+(id)alloc
{
    @synchronized([Singletonclass class])
    {
        NSAssert(_sharedobject == nil, @"Attempted to allocate a second instance of a singleton.");
        _sharedobject = [super alloc];
        return _sharedobject;
    }
   
    return nil;
}

-(id)init {
    self = [super init];
    if (self != nil) {
       
    }
   
    return self;
}


@end

ExampleViewController.h

//
// ExampleViewController.h
// SingletonClass
//
// Created by Sachin Bhardwaj on 14/12/12.
// Copyright (c) 2012 Sachin Bhardwaj. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ExampleViewController : UIViewController

{
IBOutlet UITextField *txt;
IBOutlet UIButton *btn;

}
@property (strong,nonatomic) IBOutlet UIButton *btn;
@property (strong,nonatomic) IBOutlet UITextField *txt;

-(IBAction) click;
-(IBAction)TextFieldReturn:(id)sender;


@end

ExampleViewController.m

//
//  ExampleViewController.m
//  SingletonClass
//
//  Created by Sachin Bhardwaj on 14/12/12.
//  Copyright (c) 2012 Sachin Bhardwaj. All rights reserved.
//

#import "ExampleViewController.h"
#import "Singletonclass.h"
#import "ExampleDataViewController.h"

@interface ExampleViewController ()

@end

@implementation ExampleViewController
@synthesize txt,btn;


-(IBAction) click
{
   
   
    NSString *str = txt.text;
   
  
    if([str isEqualToString:@""])
    {
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:@"enter name " delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
    else {
       
        [[Singletonclass sharedobject].array addObject:str];
        ExampleDataViewController *dt = [[ExampleDataViewController alloc]init];
        [self.navigationController pushViewController:dt animated:YES];
       
       
       
    }
}

-(IBAction)TextFieldReturn:(id)sender
{
    [sender resignFirstResponder];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
      [Singletonclass sharedobject].array = [[NSMutableArray alloc]init];
    self.title = @"Input";
}

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

@end

DataViewController.h

//
// ExampleDataViewController.h
// SingletonClass
//
// Created by Sachin Bhardwaj on 14/12/12.
// Copyright (c) 2012 Sachin Bhardwaj. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "Singletonclass.h"
@interface ExampleDataViewController : UITableViewController

@end

DataViewController.m

 

//
//  ExampleDataViewController.m
//  SingletonClass
//
//  Created by Sachin Bhardwaj on 14/12/12.
//  Copyright (c) 2012 Sachin Bhardwaj. All rights reserved.
//

#import "ExampleDataViewController.h"

@interface ExampleDataViewController ()

@end

@implementation ExampleDataViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

 
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return[[Singletonclass sharedobject].array count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
   
    cell.textLabel.text = [[Singletonclass sharedobject].array objectAtIndex: indexPath.row];   
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}

@end

Outlet Connection

outlet-connection-in-iphone.jpg

Output:

Now select which Platform you want to see output for.

Output 1 in iPhone:
output1-in-iphone.jpg 

Here we write anything in the text field and click on button to show it on the table.

Output 2 in iPhone:

output2-in-iphone.jpg

Here we write "India" and to hide the keyboard we click on the return button.

Output 3 in iPhone:

output3-in-iphone.jpg

Output show on table.

COMMENT USING

Trending up