ios Objective C 的 iPhone 开发中的“委托”是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2534094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:04:43  来源:igfitidea点击:

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

iosiphoneobjective-cdelegatesuiapplicationdelegate

提问by MikeN

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

Objective C 的 iPhone 开发中的“委托”是什么?

采纳答案by Jordan

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:

委托允许一个对象在事件发生时向另一个对象发送消息。例如,如果您使用NSURLConnection 类从网站异步下载数据。NSURLConnection 有三个常见的委托:

 - (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.

当 NSURLConnection 遇到故障、成功完成或收到来自网站的响应时,将分别调用这些委托中的一个或多个。

回答by Tyler

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 callbacksfrom a later-created object.

委托是指向具有委托持有者知道如何调用的一组方法的对象的指针。换句话说,它是一种从稍后创建的对象启用特定回调的机制

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

一个很好的例子是UIAlertView。您创建了一个UIAlertView对象来向用户显示一个短消息框,可能会为他们提供两个按钮(如“确定”和“取消”)的选择。它UIAlertView需要一种方法来回叫你,但它没有关于回叫哪个对象和调用什么方法的信息。

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

为了解决这个问题,您可以将self指针UIAlertView作为委托对象发送,作为交换,您同意(通过UIAlertViewDelegate在对象的头文件中声明 )实现一些UIAlertView可以调用的方法,例如alertView:clickedButtonAtIndex:.

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

查看这篇文章快速了解委托设计模式和其他回调技术的高级介绍

References:

参考:

回答by MikeN

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.

委托只是在某些事情发生时另一个对象向其发送消息的对象,以便委托可以处理原始对象未设计用于的特定于应用程序的细节。这是一种无需子类化即可自定义行为的方法。

回答by Felix Kling

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

我认为这篇维基百科文章最能描述它:http: //en.wikipedia.org/wiki/Delegation_pattern

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

它“只是”一种设计模式的实现,在 Objective-C 中很常见

回答by swiftBoy

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

请!查看以下简单的分步教程,了解 Delegates 在 iOS 中的工作原理。

Delegate in iOS

iOS 中的委托

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

我创建了两个 ViewControllers(用于将数据从一个发送到另一个)

  1. FirstViewController implement delegate (which provides data).
  2. SecondViewController declare the delegate (which will receive data).
  1. FirstViewController 实现委托(提供数据)。
  2. SecondViewController 声明委托(它将接收数据)。

Here is the sample code may help you.

这是示例代码可能对您有所帮助。

AppDelegate.h

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

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

第一视图控制器.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

第一视图控制器.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

第二视图控制器.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

第二视图控制器.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

回答by Milan Kamilya

I try to elaborate it through simple program

我试着通过简单的程序来阐述它

Two Classes

两班

Student.h

学生.h

#import <Foundation/Foundation.h>

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

Student.m

学生.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

老师.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

老师.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:studentwill 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.

  1. 从 main 方法什么时候initWithStudent:student执行

    1.1 教师对象的属性 ' student' 将被分配给 student 对象。

    1.2 self.student.delegate = self

        means student object's delegate will points to teacher object
    
  2. 从 main 方法何时[student studentInfo]将被调用

    2.1 [self.delegate respondToSelector:@selector(teacherName)]这里的delegate 已经指向teacher 对象,所以它可以调用'teacherName' 实例方法。

    2.2 所以[self.delegate performSelector:@selector(teacherName)]会很容易执行。

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.

这是一个相对的想法,我们看到学生对象称为“ teacherName”方法,但它基本上是由教师对象本身完成的。

回答by DrBug

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.

我认为一旦你理解了代表,所有这些答案都很有意义。就我个人而言,我来自 C/C++ 领域,在 Fortran 等过程语言之前,这里是我在 C++ 范式中寻找类似类似物的 2 分钟时间。

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

如果我要向 C++/Java 程序员解释委托,我会说

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.

什么是代表?这些是指向另一个类中的类的静态指针。一旦你分配了一个指针,你就可以调用该类中的函数/方法。因此,您的类的某些功能被“委托”(在 C++ 世界中 - 由类对象指针指向)到另一个类。

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.

我如何在 C++ 中做类似的事情?如果您尝试在 C++ 中执行此操作,您将通过在类定义中定义指向类(对象)的指针,然后将它们连接到其他类,这些类将提供附加功能作为您的基类的委托。但是这种接线需要在代码中维护,并且会很笨拙且容易出错。Objective C 只是假设程序员不擅长维护这个规则,并提供编译器限制来强制执行干净的实现。

回答by ArunHyman

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.

委托触发对象 C 中的自动事件。如果将委托设置为 Object,它会通过委托方法将消息发送到另一个对象。

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.

简单地说:委托是一种允许对象相互交互的方式,而不会在它们之间创建强大的相互依赖关系。

回答by Teja Swaroop

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

委托捕获用户的录音操作并根据用户录音操作执行特定的操作。

回答by Madhu

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.

委托只是对象的实例,我们可以代表该对象调用方法。并且还有助于在该对象的 rumtime 中创建方法。