ios 委托如何在 Objective-C 中工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1045803/
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
How does a delegate work in objective-C?
提问by Josh Bradley
- Does anyone know where I can find a good explanation/tutorial of what and how an application delegate works in
objective-C
? - The two books I have don't dwell on
delegates
enough and do not explain them very well for me to truly understand their power and function.
- 有谁知道我在哪里可以找到关于应用程序委托的工作方式和工作方式的很好的解释/教程
objective-C
? - 我所拥有的两本书并没有详细说明
delegates
,也没有很好地解释它们,让我真正了解它们的力量和功能。
回答by Alex Rozanski
When in doubt, check the docs!
如有疑问,请查看文档!
Basically, delegation is a way of allowing objects to interact with each other without creating strong interdependencies between them, since this makes the design of your application less flexible. Instead of objects controlling one another, they can have a delegate which they send (or delegate) messages to, and the delegate does whatever they do, in order to respond and act to this message, and then usually return something back to the other object.
基本上,委托是一种允许对象相互交互的方式,而不会在它们之间创建强大的相互依赖性,因为这会降低应用程序的设计灵活性。不是对象控制彼此,它们可以有一个委托,它们可以向其发送(或委托)消息,委托会做任何事情,以响应并对该消息采取行动,然后通常将某些东西返回给另一个对象.
Delegation is also a better alternative to subclassing. Instead of you having to create your own custom classes to slightly alter the way that other objects behave, or pass them data, delegation allows objects to send messages to their delegates to do work for them without the overhead of creating subclasses to make minor changes to other objects.
委托也是子类化的更好选择。您不必创建自己的自定义类来稍微改变其他对象的行为方式或将数据传递给它们,委托允许对象向其委托发送消息以为它们工作,而无需创建子类以对它们进行细微更改其他对象。
Of course, the main disadvantage of delegation is that the delegate methods available are dependent on what the Apple engineers foresee as being useful and what common implementations they expect people to need, which imposes a restriction on what you can achieve. Although, as Quinn Taylor pointed out, this is specific to the Cocoa frameworks and so doesn't apply in all situations.
当然,委托的主要缺点是可用的委托方法取决于 Apple 工程师认为有用的内容以及他们期望人们需要的常见实现,这对您可以实现的目标施加了限制。虽然,正如 Quinn Taylor 所指出的,这是 Cocoa 框架所特有的,因此并不适用于所有情况。
If delegation is an option over subclassing, then take it, because it's a much cleaner way to manage your code and interactions between objects.
如果委派是子类化的一种选择,那么就采用它,因为它是管理代码和对象之间交互的更简洁的方式。
回答by Steve Ives
As described above, a delegate is not a feature of iOS or Objective-C, but just a programming technique and requires no specific language support.
如上所述,委托不是 iOS 或 Objective-C 的功能,而只是一种编程技术,不需要特定的语言支持。
A class (e,g, classA) may be written such that its getDataand doSomethingmethods can be implemented not by itself, but by a delegate (perhaps because classA doesn't know what the data will be or what it will have to do).
一个类(例如,classA)可以这样写,它的getData和doSomething方法可以不是由它自己实现,而是由一个委托实现(也许是因为 classA 不知道数据是什么或它必须做什么) )。
To achieve this, classA provides a property, usually called delegate, (which is just a pointer to the class - the delegate - that implements the delegated methods) and then, when it wants to call those methods, it actually calls the methods in the delegate:
为了实现这一点, classA 提供了一个属性,通常称为delegate,(它只是一个指向类的指针 - 委托 - 实现委托的方法)然后,当它想要调用这些方法时,它实际上调用了代表:
[self.delegate getData];
and
和
[self.delegate doSomething];
self.delegate
may be initially set to self
:
self.delegate
可能最初设置为self
:
self.delegate = self;
i.e. classA implements it's own version of these methods, unless they are delegated.
即 classA 实现它自己版本的这些方法,除非它们被委托。
Any other class, wanting to be the implementor of the methods (i.e. to be the delegate and possibly override classA's default implementation), would first set classA's delegate to be itself. so if classB wanted to be the delegate for these methods, in classB, we would have:
任何其他类,想要成为方法的实现者(即成为委托并可能覆盖 classA 的默认实现),首先将 classA 的委托设置为它自己。所以如果 classB 想成为这些方法的委托,在 classB 中,我们将:
classA.delegate = self;
So when classA calls these delegated methods, it's actually calling classB to implement these methods, without knowing anything about classB or even that it exists and classB doesn't have to sub-class classA.
因此,当 classA 调用这些委托方法时,它实际上是在调用 classB 来实现这些方法,而不知道有关 classB 的任何信息,甚至不知道 classB 的存在并且 classB 不必对 classA 进行子类化。
The limitation is that classB can only override methods which classA wants to delegate - with subclassing, you can override any method.
限制是 classB 只能覆盖 classA 想要委托的方法 - 通过子类化,您可以覆盖任何方法。
Protocolsare used to formalise the delegation process by defining a list of methods which either mustbe implemented by the delegate (the delegator provides no default version of the method and the method must be implemented somewhere) or can be optionally implemented by the delegate (i.e. the delegator has it's own version or it does not matter if the method is not implemetned).
协议用于通过定义必须由委托实现的方法列表来形式化委托过程(委托方不提供该方法的默认版本并且该方法必须在某处实现)或可以由委托可选地实现(即委托人有它自己的版本,或者如果该方法没有实现则无关紧要)。
回答by sourabh rajput
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 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 :::
解释 :::
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
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.
当 initWithStudent:student 将执行时,从 main 方法开始
1.1 教师对象的属性 'student' 将被赋值为 student 对象。
1.2 self.student.delegate = self 表示学生对象的委托将指向教师对象
从调用 [student studentInfo] 时的 main 方法
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 Frank
Just imagine that you call by phone, and order a pizza. Then, a pizza delivery boy arrives to your home (this is a Delegate), and when you pay for the pizza, the delivery pizza boy returns the money to his restaurant.
试想一下,您通过电话拨打电话并订购比萨饼。然后,一个比萨饼送货员到达您家(这是一个代表),当您支付比萨饼时,比萨饼送货员将钱退还给他的餐厅。
you = object delivery boy = Delegate restaurant = object
你 = 对象送货员 = 代表餐厅 = 对象