What is a "delegate" in Objective C's iPhone development?

IosIphoneObjective CDelegatesUiapplicationdelegate

Ios Problem Overview


What is a "delegate" in Objective C's iPhone development?

Ios Solutions


Solution 1 - Ios

A delegate is a pointer to an object with a set of methods the delegate-holder knows how to call. In other words, it's a mechanism to enable specific callbacks from a later-created object.

A good example is UIAlertView. You create a UIAlertView object to show a short message box to users, possibly giving them a choice with two buttons like "OK" and "Cancel". The UIAlertView needs a way to call you back, but it has no information of which object to call back and what method to call.

To solve this problem, you can send your self pointer to UIAlertView as a delegate object, and in exchange you agree (by declaring the UIAlertViewDelegate in your object's header file) to implement some methods that UIAlertView can call, such as alertView:clickedButtonAtIndex:.

Check out this post for a quick high-level intro to the delegate design pattern and other callback techniques.

References:

Solution 2 - Ios

See this discussion

A delegate allows one object to send messages to another object when an event happens. For example, if you're downloading data from a web site asynchronously using the NSURLConnection class. NSURLConnection has three common delegates:

 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

One or more of these delegates will get called when NSURLConnection encounters a failure, finishes successfully, or received a response from the web site, respectively.

Solution 3 - Ios

Delegates are a design pattern; there is no special syntax or language support.

A delegate is just an object that another object sends messages to when certain things happen, so that the delegate can handle app-specific details the original object wasn't designed for. It's a way of customizing behavior without subclassing.

Solution 4 - Ios

I think this Wikipedia article describes it best: http://en.wikipedia.org/wiki/Delegation_pattern

It is "just" an implementation of a design pattern and very common in Objective-C

Solution 5 - Ios

Please! check below simple step by step tutorial to understand how Delegates works in iOS.

> Delegate in iOS

I have created two ViewControllers (for sending data from one to another)

  1. FirstViewController implement delegate (which provides data).
  2. SecondViewController declare the delegate (which will receive data).

Here is the sample code may help you.

AppDelegate.h


#import <UIKit/UIKit.h>

@class FirstViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) FirstViewController *firstViewController;

@end

AppDelegate.m


#import "AppDelegate.h"
#import "FirstViewController.h"

@implementation AppDelegate

@synthesize firstViewController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    
    //create instance of FirstViewController
    firstViewController = [[FirstViewController alloc] init];
    
    //create UINavigationController instance using firstViewController
    UINavigationController *firstView = [[UINavigationController alloc] initWithRootViewController:firstViewController];
    
    //added navigation controller to window as a rootViewController
    self.window.rootViewController = firstView;
    
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end

FirstViewController.h


#import <UIKit/UIKit.h>
#import "SecondViewController.h"

@interface FirstViewController : UIViewController<MyDelegate>

@property (nonatomic, retain) NSString *mesasgeData;

@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UIButton *nextButton;

- (IBAction)buttonPressed:(id)sender;

@property (nonatomic, strong) SecondViewController *secondViewController;

@end

FirstViewController.m


#import "FirstViewController.h"

@interface FirstViewController ()
@end

@implementation FirstViewController

@synthesize mesasgeData;
@synthesize textField;
@synthesize secondViewController;

#pragma mark - View Controller's Life Cycle methods

- (void)viewDidLoad
{
    [super viewDidLoad];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
}

#pragma mark - Button Click event handling method

- (IBAction)buttonPressed:(id)sender {
    
    //get the input data from text feild and store into string
    mesasgeData = textField.text;
    
    //go keypad back when button clicked from textfield
    [textField resignFirstResponder];
    
    //crating instance of second view controller
    secondViewController = [[SecondViewController alloc]init];
    
    //it says SecondViewController is implementing MyDelegate
    secondViewController.myDelegate = self;
    
    //loading new view via navigation controller
    [self.navigationController pushViewController:secondViewController animated:YES];    
}

#pragma mark - MyDelegate's method implementation

-(NSString *) getMessageString{
    return mesasgeData;
}

@end

SecondViewController.h


//declare our own delegate
@protocol MyDelegate <NSObject>

-(NSString *) getMessageString;

@end

#import <UIKit/UIKit.h>

@interface SecondViewController : UIViewController

@property (weak, nonatomic) IBOutlet UILabel *messageLabel;

@property (nonatomic, retain) id <MyDelegate> myDelegate;

@end

SecondViewController.m


#import "SecondViewController.h"

@interface SecondViewController ()
@end

@implementation SecondViewController

@synthesize messageLabel;
@synthesize myDelegate;

- (void)viewDidLoad
{
    [super viewDidLoad];    
    messageLabel.text = [myDelegate getMessageString];    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end

Solution 6 - Ios

I think all these answers make a lot of sense once you understand delegates. Personally I came from the land of C/C++ and before that procedural languages like Fortran etc so here is my 2 min take on finding similar analogues in C++ paradigm.

If I were to explain delegates to a C++/Java programmer I would say

What are delegates ? These are static pointers to classes within another class. Once you assign a pointer, you can call functions/methods in that class. Hence some functions of your class are "delegated" (In C++ world - pointer to by a class object pointer) to another class.

What are protocols ? Conceptually it serves as similar purpose as to the header file of the class you are assigning as a delegate class. A protocol is a explicit way of defining what methods needs to be implemented in the class who's pointer was set as a delegate within a class.

How can I do something similar in C++? If you tried to do this in C++, you would by defining pointers to classes (objects) in the class definition and then wiring them up to other classes that will provide additional functions as delegates to your base class. But this wiring needs to be maitained within the code and will be clumsy and error prone. Objective C just assumes that programmers are not best at maintaining this decipline and provides compiler restrictions to enforce a clean implementation.

Solution 7 - Ios

I try to elaborate it through simple program

Two Classes

Student.h

#import <Foundation/Foundation.h>

@interface Student : NSObject
@property (weak) id  delegate;
- (void) studentInfo;
@end

Student.m

#import "Student.h"
@implementation Student
- (void) studentInfo
{
    NSString *teacherName;
    if ([self.delegate respondsToSelector:@selector(teacherName)]) {
        teacherName = [self.delegate performSelector:@selector(teacherName)];
    }
    NSLog(@"\n Student name is XYZ\n Teacher name is %@",teacherName);
}
@end

Teacher.h

#import <Foundation/Foundation.h>
#import "Student.h>

@interface Teacher: NSObject
@property (strong,nonatomic) Student *student;
- (NSString *) teacherName;
- (id) initWithStudent:(Student *)student;
@end

Teacher.m

#import "Teacher.h"

@implementation Teacher

- (NSString *) teacherName
{
    return @"ABC";
}
- (id) initWithStudent:(Student *)student
{
    self = [ super init];
    if (self) {
        self.student = student;
        self.student.delegate = self;
    }
    return self;
}
@end

main.m

#import <Foundation/Foundation.h>
#import "Teacher.h"
int main ( int argc, const char* argv[])
{
    @autoreleasepool {
        
        Student *student = [[Student alloc] init];
        Teacher *teacher = [[Teacher alloc] initWithStudent:student];
        
        [student studentInfo];

    }
    return 0;
}

EXPLANATION :::

  1. From main method when initWithStudent:student will execute

    1.1 Teacher's object's property 'student' will be assigned with student object.

    1.2 self.student.delegate = self

      means student object's delegate will points to teacher object
    
  2. From main method when [student studentInfo] will be called

    2.1 [self.delegate respondToSelector:@selector(teacherName)] Here delegate already points to teacher object so it can invoke 'teacherName' instance method.

    2.2 so [self.delegate performSelector:@selector(teacherName)] will execute easily.

It looks like Teacher object assign delegate to student object to call it's own method.

It is a relative idea, where we see that student object called 'teacherName' method but it is basically done by teacher object itself.

Solution 8 - Ios

The delegate fires the automatic events in Objects C. If you set the delegate to Object, it sends the message to another object through the delegate methods.

It's a way to modify the behavior of a class without requiring subclassing.

Each Objects having the delegate methods.These delegate methods fires, when the particular Objects take part in user interaction and Program flow cycle.

Simply stated: delegation is a way of allowing objects to interact with each other without creating strong interdependencies between them.

Solution 9 - Ios

A delegate captures the taping actions of an user and performs particular Action according to the user Taping Action.

Solution 10 - Ios

Delegate is nothing but instance of Object which we can call methods behalf of that Objects. and also helps to create methods in rumtime of that Objects.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMikeNView Question on Stackoverflow
Solution 1 - IosTylerView Answer on Stackoverflow
Solution 2 - IosJordanView Answer on Stackoverflow
Solution 3 - IosMikeNView Answer on Stackoverflow
Solution 4 - IosFelix KlingView Answer on Stackoverflow
Solution 5 - IosswiftBoyView Answer on Stackoverflow
Solution 6 - IosDrBugView Answer on Stackoverflow
Solution 7 - IosMilan KamilyaView Answer on Stackoverflow
Solution 8 - IosArunjackView Answer on Stackoverflow
Solution 9 - IosTeja SwaroopView Answer on Stackoverflow
Solution 10 - IosMadhuView Answer on Stackoverflow