Posted By Our Mentors
Amreen Khan
Android Developer
animesh bansal
iphone App Developer
Devendra chouksey
Android Developer
Dilip Saket
IOS apps developer
Hemraj Jhariya
iOS Developer
Jaihind singh Rajput
Smart Phone App Dev
Mujahid khan
Android developer
Narendra Yadav
android developer
Narinder Gupta
Mobile App Architect
Pradeep singh Thakur
Mobile App Architect
Sanjay Sharma
Andriod Developer
Shakti Rajpal
IT Architect
Soniya Vishwakarma
iPhone App Developer
Sunil Raghuwanshi
iPhone App Developer
Supriya Kapse
Senior developer
Delegate Method In Objective C - User Defined Iphone/iPad
how to create your own delegate method to transfer message from one class to another class
Posted By: animesh bansal Date: 29 Dec 2013 View: 1485
      Rate This !!

Download the source code

 

 

Coding pattern is one of the most developers take venerated and why not it is only a weapon to showcase whatever they want in result. While slip-ups and trials with a coding pattern are nothing new and this is only a way to come out with the greatest outputs. While the mobile apps on to the race, apple itself has been provided its own platform to use and lot of methods to make them fabricated and further submitted for the user compliance. In same sequence, apple has also been announced delegate – a method to call objects and to make their harmony in successful manner.

So Delegate, what actually?

In a simple way delegate is a medium by which objects can interact to each other in a ViewController. This can basically be used in formulation of iphone/ipad applications to enable the ease to developers while transferring messages from one controller to another in a ChildView.

There are many cases in which developers get wedged when child has to transfer data to its parent.

Delegation is a simple and powerful pattern in which one object in a program acts on behalf of or in coordination with another object. The delegating object keeps a reference to the other object—the delegate—and at the appropriate time sends a message to it. The message informs the delegate of an event that the delegating object is about to handle or has just been handled. The delegate may respond to the message by updating the appearance or state of itself or other objects in the application and in some cases it can return a value that affects how an impending event is being handled. The main value of delegation is that it allows you to easily customize the behavior of several objects in one central object.

Why It Is Needed To Use with the Project

Actually data transfer is a one way in Objective-C means Parent can transfer any message to its child but child cannot transfer its own, transferring massages to its parent that is a one way route, to achieve two way communication we use delegate method like UITableView, UIWebView , UIScrollView and other likewise.

Delegate is a best way to make notification from one controller to another and it is a very flexible method to transfer data or to implement customized methods of data transfer. These methods are really useful when using web services to notify whether the response is positive or negative. In negative means web service gives error such as network error and other kinda realted whereas it enables successful response is case of being positive.    

 

 

Declaring the Delegate Methods:-

The delegate's methods are declared starting with @protocol. The protocol MyViewOfColorDelegate conforms to the NSObject protocol for a specific reason. The NSObject protocol contains a method, respondsToSelector:, that can be used to ensure the delegate object actually implements an optional method before the method is called. Calling a method that isn't implemented by the delegate object will cause an application to crash.

 

 

Creating the Setters and Getters:-

Finish by synthesizing the setter and getter methods. Type the following code just below the instance variable closing brace.

@property (nonatomic, assign) id <selectcolorDelegate> delegate;

If you are using ARC, type the following code instead:

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

Click on "MTSlider.m" and type the following code just below @implementation to complete the property.

@synthesize delegate;

 

 

Step :1

 

1) Launch a Xcode and create a new project with a new Project with a singleView template which will work as entry point for project and give delegateUseViewController as project name and class prefix as  delegateUseViewController. Uncheck StoryBord if you want you you can use StoryBord also ,Uncheck UnitTest option and let ARC remain checked. You can use target device as iPhone and iPad any,but in this example i am using iPhone Save the project in your desired location.

 

 

#import <UIKit/UIKit.h>

 

//importing view where we had created delegate method

#import "selectcolor.h"

//delegate method which we had created is to be used 

@interface delegateUseViewController : UIViewController<selectcolorDelegate>

{

// view which has to be used act as child class in which i had used table and in that table name of the color when user select it will pass to its parent class the color name

    selectcolor *viewSelectColor;

//label that will display name of color which user had selected

    UILabel *lblColor;

}

@end

 

 

 

 

 

#import "delegateUseViewController.h"

 

@interface delegateUseViewController ()

 

@end

 

@implementation delegateUseViewController

 

- (void)viewDidLoad

{

    [super viewDidLoad];

    [self screenDesigning];

   

// Do any additional setup after loading the view, typically from a nib.

}

 

//screen designing of view where we had mad table and on clicking delegate method called and passe value to its parent class.

 

-(void)screenDesigning{

    

    lblColor =[[UILabel alloc]init];

    lblColor.frame=CGRectMake(10, 200, 736, 50);

    lblColor.textColor=[UIColor blackColor];

    lblColor.text=@"Select color";

    lblColor.textAlignment=NSTextAlignmentCenter;

    lblColor.backgroundColor=[UIColor clearColor];

     lblColor.font=[UIFont fontWithName:@"Arial" size:30];

    [self.view addSubview:lblColor];

    

    

    viewSelectColor =[[selectcolor alloc]init];

    //we are useing delegate method of the class

    viewSelectColor.delegate=self;

    viewSelectColor.backgroundColor=[UIColor grayColor];

    viewSelectColor.frame=CGRectMake(10,640, 736,400);

    [self.view addSubview:viewSelectColor];

    

    

}

 

//delegate method which will passing value to its parent class

which will be called automaticaley and contain value as string parameter name of the color 

 

- (void) selectedColor:(NSString *)colorName{

   

    

    if ([colorName isEqualToString:@"Red"]) {

        lblColor.textColor=[UIColor redColor];

        lblColor.text=@"you had selected red color";

        

    }

    if ([colorName isEqualToString:@"green"]) {

         lblColor.textColor=[UIColor greenColor];

        lblColor.text=@"you had selected green color";

        

    }

    if ([colorName isEqualToString:@"yellow"]) {

        lblColor.textColor=[UIColor yellowColor];

        lblColor.text=@"you had selected yellow color";

        

    }

    if ([colorName isEqualToString:@"blue"]) {

        lblColor.textColor=[UIColor blueColor];

        lblColor.text=@"you had selected blue color";

        

    }

    if ([colorName isEqualToString:@"black"]) {

        lblColor.textColor=[UIColor blackColor];

        lblColor.text=@"you had selected black color";

        

    }

    if ([colorName isEqualToString:@"purple"]) {

        lblColor.textColor=[UIColor purpleColor];

        lblColor.text=@"you had selected purple color";

        

    }

   

 

}

 

 

 

- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

 

 

 

Step :2 create another view in which we are declaring and defining delegate here i had named selectcolor

 

//synthesize the delegate method

@synthesize delegate;

- (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        // Initialization code

        arrColor=[[NSMutableArray alloc]init];

        [self fillingArrayDataWithColor];

        [self screenDesigningForExplainingScreenDesigning];

    }

    return self;

}

 

//filling array that contain color name

-(void)fillingArrayDataWithColor{

    

    [arrColor addObject:@"Red"];

    [arrColor addObject:@"green"];

    [arrColor addObject:@"yellow"];

    [arrColor addObject:@"blue"];

    [arrColor addObject:@"black"];

    [arrColor addObject:@"purple"];

    

    

}

 

-(void)screenDesigningForExplainingScreenDesigning{

    

    lblSelectColor =[[UILabel alloc]init];

    lblSelectColor.frame=CGRectMake(10, 0, 736, 30);

    lblSelectColor.textColor=[UIColor blackColor];

    lblSelectColor.text=@"color changes based on its child view interaction";

    lblSelectColor.textAlignment=NSTextAlignmentCenter;

    lblSelectColor.backgroundColor=[UIColor clearColor];

    [self addSubview:lblSelectColor];

    

    tblTestList=[[UITableView alloc] initWithFrame:CGRectMake(10,30, 736,400) style:UITableViewStylePlain];

    tblTestList.allowsSelection = YES;

    tblTestList.delegate=self;

    tblTestList.dataSource=self;

    tblTestList.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"QuestionTableImageBackGround.png"]];

    tblTestList.showsHorizontalScrollIndicator=NO;

    tblTestList.showsVerticalScrollIndicator=NO;

    [self addSubview:tblTestList];

    

    

}

#pragma mark table data source and delegate

 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return 1;

}

 

 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 35;

}

 

 

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

{

    

    

    return [arrColor count];

}

 

 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    NSString *CellIdentifier =[NSString stringWithFormat:@"cellExamPattern%d",indexPath.row];

    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    }

    

    

    cell.textLabel.text=[arrColor objectAtIndex:indexPath.row];

    

    cell.textLabel.highlightedTextColor=[UIColor whiteColor];

    cell.textLabel.backgroundColor=[UIColor clearColor];

    

    

    return cell;

}

 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    

    

    NSString *strColorName=[arrColor objectAtIndex:indexPath.row];

    

   //this method is called and passed value to its parent class when ever user select table color of its child

    

    if(self.delegate!=nil && [(id)[self delegate] respondsToSelector:@selector(selectedColor:)])

    {

        [(id)[self delegate] selectedColor:strColorName ];

    }

 

}

 

 

 

I cheated on my boyfriend read open

Posted Queries
Posted By: Remus Cicu Reply:Delegate Method In Objective C - User Define
05 Feb 2014
I'm trying to download the same project put i get a file with the extension .fla , why is that?
I cheated on my boyfriend men and women open