我知道代表如何工作,也知道如何使用它们。

但我该如何创建它们呢?

有帮助吗?

解决方案

Objective-C委托是一个已分配给delegate属性另一个对象的对象。要创建一个,只需定义一个实现您感兴趣的委托方法的类,并将该类标记为实现委托协议。

例如,假设您有UIWebView。如果你想实现其代理人的 webViewDidStartLoad: 方法,你可以创建一个这样的类:

@interface MyClass<UIWebViewDelegate>
// ...
@end

@implementation MyClass
- (void)webViewDidStartLoad:(UIWebView *)webView { 
    // ... 
}
@end

然后你可以创建一个MyClass实例并将其指定为Web视图的委托:

MyClass *instanceOfMyClass = [[MyClass alloc] init];
myWebView.delegate = instanceOfMyClass;

respondsToSelector:方面,它可能具有与此类似的代码,以查看委托是否使用weak消息/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/respondsToSelector:“rel =”noreferrer“> assign 并在适当的时候发送。

if([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
    [self.delegate webViewDidStartLoad:self];
}

委托属性本身通常声明为UIWebViewDelegate(在ARC中)或@optional(在ARC之前)以避免保留循环,因为对象的委托通常持有对该对象的强引用。 (例如,视图控制器通常是它包含的视图的委托。)

为您的班级制作代表

要定义自己的代理,您必须在某处声明其方法,如 btnI“rel =”noreferrer“>协议上的Apple文档。您通常会声明一个正式的协议。从UIWebView.h转述的声明如下所示:

@protocol UIWebViewDelegate <NSObject>
@optional
- (void)webViewDidStartLoad:(UIWebView *)webView;
// ... other methods here
@end

这类似于接口或抽象基类,因为它为您的委托创建了一种特殊类型,在这种情况下为-respondsToSelector:。代表实施者必须采用该协议:

@interface MyClass <UIWebViewDelegate>
// ...
@end

然后实现协议中的方法。对于在协议中声明为loadStarted的方法(与大多数委托方法一样),您需要在调用特定方法之前使用delegateRespondsTo进行检查。

命名

委托方法通常以委托类名开头,并将委托对象作为第一个参数。他们也经常使用意志,应该或形式。因此,NSObject(第一个参数是Web视图)而不是CALayer(不带参数)。

速度优化

您可以在设置委托时缓存该信息,而不是每当我们想要发送消息时检查委托是否响应选择器。一种非常简洁的方法是使用位域,如下所示:

@protocol SomethingDelegate <NSObject>
@optional
- (void)something:(id)something didFinishLoadingItem:(id)item;
- (void)something:(id)something didFailWithError:(NSError *)error;
@end

@interface Something : NSObject
@property (nonatomic, weak) id <SomethingDelegate> delegate;
@end

@implementation Something {
  struct {
    unsigned int didFinishLoadingItem:1;
    unsigned int didFailWithError:1;
  } delegateRespondsTo;
}
@synthesize delegate;

- (void)setDelegate:(id <SomethingDelegate>)aDelegate {
  if (delegate != aDelegate) {
    delegate = aDelegate;

    delegateRespondsTo.didFinishLoadingItem = [delegate respondsToSelector:@selector(something:didFinishLoadingItem:)];
    delegateRespondsTo.didFailWithError = [delegate respondsToSelector:@selector(something:didFailWithError:)];
  }
}
@end

然后,在正文中,我们可以检查我们的委托是通过访问我们的displayLayer:结构来处理消息,而不是一遍又一遍地发送<=>。

非正式代表

在协议存在之前,通常使用

其他提示

批准的答案很棒,但如果您正在寻找1分钟的答案,请尝试以下方法:

MyClass.h文件应如下所示(添加带注释的委托行!)

#import <BlaClass/BlaClass.h>

@class MyClass;             //define class, so protocol can see MyClass
@protocol MyClassDelegate <NSObject>   //define delegate protocol
    - (void) myClassDelegateMethod: (MyClass *) sender;  //define delegate method to be implemented within another class
@end //end protocol

@interface MyClass : NSObject {
}
@property (nonatomic, weak) id <MyClassDelegate> delegate; //define MyClassDelegate as delegate

@end

MyClass.m文件应如下所示

#import "MyClass.h"
@implementation MyClass 
@synthesize delegate; //synthesise  MyClassDelegate delegate

- (void) myMethodToDoStuff {
    [self.delegate myClassDelegateMethod:self]; //this will call the method implemented in your other class    
}

@end

在另一个类中使用你的委托(在这种情况下称为MyVC的UIViewController)MyVC.h:

#import "MyClass.h"
@interface MyVC:UIViewController <MyClassDelegate> { //make it a delegate for MyClassDelegate
}

MyVC.m:

myClass.delegate = self;          //set its delegate to self somewhere

实施委托方法

- (void) myClassDelegateMethod: (MyClass *) sender {
    NSLog(@"Delegates are great!");
}

当使用正式的协议方法创建委托支持时,我发现你可以通过添加类似的东西来确保正确的类型检查(尽管是运行时,而不是编译时间):

if (![delegate conformsToProtocol:@protocol(MyDelegate)]) {
    [NSException raise:@"MyDelegate Exception"
                format:@"Parameter does not conform to MyDelegate protocol at line %d", (int)__LINE__];
}

在您的委托访问者(setDelegate)代码中。这有助于减少错误。

也许这更像是你所缺少的:

如果你来自C ++这样的观点,代表们会习惯一点 - 但基本上“他们只是工作”。

它的工作方式是你设置一些你编写为NSWindow的委托的对象,但是你的对象只有许多可能的委托方法中的一个或几个的实现(方法)。所以发生了一些事情,并且 NSWindow 想要调用你的对象 - 它只是使用Objective-c的 respondsToSelector 方法来确定你的对象是否想要调用该方法,然后调用它。这就是Objective-c的工作原理 - 根据需要查找方法。

用你自己的对象做这件事是完全无关紧要的,没有什么特别的事情,例如你可以有27个对象的 NSArray ,所有不同类型的对象,只有18个他们有方法 - (void)setToBue; 其他9则没有。所以在所有需要它的18个上调用 setToBlue ,就像这样:

for (id anObject in myArray)
{
  if ([anObject respondsToSelector:@selector(@"setToBlue")])
     [anObject setToBlue]; 
}

关于委托的另一个问题是它们没有被保留,所以你总是必须在 MyClass dealloc 方法中将委托设置为 nil

作为Apple推荐的一种良好做法,代表(根据定义,这是一种协议)符合 NSObject 协议。

@protocol MyDelegate <NSObject>
    ...
@end

&安培;要在您的委托中创建可选方法(即不一定需要实现的方法),您可以使用 @optional 注释,如下所示:

@protocol MyDelegate <NSObject>
    ...
    ...
      // Declaration for Methods that 'must' be implemented'
    ...
    ...
    @optional
    ...
      // Declaration for Methods that 'need not necessarily' be implemented by the class conforming to your delegate
    ...
@end

因此,当使用已指定为可选的方法时,如果视图(符合您的委托)实际实现了可选方法,则需要(在您的类中)检查 respondsToSelector ( s)与否。

我认为,一旦你理解了代表,所有这些答案都很有意义。就个人而言,我来自C / C ++之前,而且在Fortran之类的程序语言之前,所以这是我在C ++范式中找到类似类比的2分钟。

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

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

什么是协议? 从概念上讲,它的作用与您指定为委托类的类的头文件类似。协议是一种明确的方法,用于定义需要在类中实现哪些方法的指针被设置为类中的委托。

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

迅捷版

委托只是一个为另一个类做一些工作的类。阅读以下代码,了解一个有点愚蠢(但希望有启发性)的 Playground 示例,该示例展示了如何在 Swift 中完成此操作。

// A protocol is just a list of methods (and/or properties) that must
// be used by any class that adopts the protocol.
protocol OlderSiblingDelegate: class {
    // This protocol only defines one required method
    func getYourNiceOlderSiblingAGlassOfWater() -> String
}

class BossyBigBrother {

    // The delegate is the BossyBigBrother's slave. This position can 
    // be assigned later to whoever is available (and conforms to the 
    // protocol).
    weak var delegate: OlderSiblingDelegate?

    func tellSomebodyToGetMeSomeWater() -> String? {
        // The delegate is optional because there might not be anyone
        // nearby to boss around.
        return delegate?.getYourNiceOlderSiblingAGlassOfWater()
    }
}

// PoorLittleSister conforms to the OlderSiblingDelegate protocol
class PoorLittleSister: OlderSiblingDelegate {

    // This method is repquired by the protocol, but the protocol said
    // nothing about how it needs to be implemented.
    func getYourNiceOlderSiblingAGlassOfWater() -> String {
        return "Go get it yourself!"
    }

}

// initialize the classes
let bigBro = BossyBigBrother()
let lilSis = PoorLittleSister()

// Set the delegate 
// bigBro could boss around anyone who conforms to the 
// OlderSiblingDelegate protocol, but since lilSis is here, 
// she is the unlucky choice.
bigBro.delegate = lilSis

// Because the delegate is set, there is a class to do bigBro's work for him.
// bigBro tells lilSis to get him some water.
if let replyFromLilSis = bigBro.tellSomebodyToGetMeSomeWater() {
    print(replyFromLilSis) // "Go get it yourself!"
}

在实际应用中,委托常用于以下几种情况

  1. 当一个类需要向另一个类传达一些信息时
  2. 当一个类想要允许另一个类自定义它时

除了委托类符合所需的协议之外,这些类不需要事先了解彼此的任何信息。

我强烈建议阅读以下两篇文章。他们帮助我比其他人更好地了解代表 文档 做过。

好的,这不是问题的真正答案,但是如果你正在查找如何制作自己的代表,那么更简单的东西可能是更好的答案。

我很难实现我的代表,因为我很少需要。我只能拥有一个委托对象的委托。因此,如果您希望您的代表以单向方式进行通信/传递数据,而不是通过通知更好。

NSNotification可以将对象传递给多个收件人,并且它非常易于使用。 它的工作原理如下:

MyClass.m文件应如下所示

#import "MyClass.h"
@implementation MyClass 

- (void) myMethodToDoStuff {
//this will post a notification with myClassData (NSArray in this case)  in its userInfo dict and self as an object
[[NSNotificationCenter defaultCenter] postNotificationName:@"myClassUpdatedData"
                                                    object:self
                                                  userInfo:[NSDictionary dictionaryWithObject:selectedLocation[@"myClassData"] forKey:@"myClassData"]];
}
@end

要在其他课程中使用您的通知: 添加类作为观察者:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(otherClassUpdatedItsData:) name:@"myClassUpdatedData" object:nil];

实施选择器:

- (void) otherClassUpdatedItsData:(NSNotification *)note {
    NSLog(@"*** Other class updated its data ***");
    MyClass *otherClass = [note object];  //the object itself, you can call back any selector if you want
    NSArray *otherClassData = [note userInfo][@"myClassData"]; //get myClass data object and do whatever you want with it
}

如果

,请不要忘记以观察员的身份删除您的班级
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

假设您开发了一个类,并希望声明一个委托属性,以便能够在发生某些事件时通知它:

@class myClass;

@protocol myClassDelegate <NSObject>

-(void)myClass:(MyClass*)myObject requiredEventHandlerWithParameter:(ParamType*)param;

@optional
-(void)myClass:(MyClass*)myObject optionalEventHandlerWithParameter:(ParamType*)param;

@end


@interface MyClass : NSObject

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

@end

所以你声明一个协议 MyClass 头文件(或单独的头文件),并声明您的委托必须/应该实现的必需/​​可选事件处理程序,然后在中声明一个属性 MyClass 类型(id< MyClassDelegate>) 表示任何符合协议的目标c类 MyClassDelegate ,您会注意到委托属性被声明为weak,这对于防止保留周期非常重要(大多数情况下委托保留 MyClass 例如,如果您将委托声明为保留,则它们都将相互保留,并且都不会被释放)。

您还会注意到协议方法传递了 MyClass 委托的实例作为参数,这是最佳实践,以防委托想要调用某些方法 MyClass 实例,并且当委托将自己声明为 MyClassDelegate 到多个 MyClass 实例,比如当你有多个 UITableView's 你的实例 ViewController 并宣称自己是 UITableViewDelegate 对他们所有人。

并在你的里面 MyClass 您通知代表已声明的事件,如下所示:

if([_delegate respondsToSelector:@selector(myClass: requiredEventHandlerWithParameter:)])
{
     [_delegate myClass:self requiredEventHandlerWithParameter:(ParamType*)param];
}

您首先检查您的委托是否响应您将要调用的协议方法,以防委托未实现它并且应用程序将崩溃(即使需要协议方法)。

这是创建委托的简单方法

在.h文件中创建协议。确保在协议之前使用@class定义了UIViewController &lt;的名称。我将要使用的协议是UIViewController类&gt;。

步骤:1:创建一个名为“YourViewController”的新类协议它将是UIViewController类的子类,并将此类分配给第二个ViewController。

步骤:2:转到“YourViewController”文件并修改如下:

#import <UIKit/UIkit.h>
@class YourViewController;

@protocol YourViewController Delegate <NSObject>

 @optional
-(void)defineDelegateMethodName: (YourViewController *) controller;

@required
-(BOOL)delegateMethodReturningBool: (YourViewController *) controller;

  @end
  @interface YourViewController : UIViewController

  //Since the property for the protocol could be of any class, then it will be marked as a type of id.

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

@end

协议行为中定义的方法可以使用@optional和@required作为协议定义的一部分进行控制。

步骤:3: 代表的实施

    #import "delegate.h"

   @interface YourDelegateUser ()
     <YourViewControllerDelegate>
   @end

   @implementation YourDelegateUser

   - (void) variousFoo {
      YourViewController *controller = [[YourViewController alloc] init];
      controller.delegate = self;
   }

   -(void)defineDelegateMethodName: (YourViewController *) controller {
      // handle the delegate being called here
   }

   -(BOOL)delegateMethodReturningBool: (YourViewController *) controller {
      // handle the delegate being called here
      return YES;
   }

   @end

//在调用之前测试方法是否已定义

 - (void) someMethodToCallDelegate {
     if ([[self delegate] respondsToSelector:@selector(defineDelegateMethodName:)]) {
           [self.delegate delegateMethodName:self]; 
     }
  }

要创建自己的委托,首先需要创建协议并声明必要的方法,而不实现。然后将此协议实现到要在其中实现委托或委托方法的头类中。

协议必须声明如下:

@protocol ServiceResponceDelegate <NSObject>

- (void) serviceDidFailWithRequestType:(NSString*)error;
- (void) serviceDidFinishedSucessfully:(NSString*)success;

@end

这是应该完成某项任务的服务类。它显示了如何定义委托以及如何设置委托。在任务完成后的实现类中,委托调用方法。

@interface ServiceClass : NSObject
{
id <ServiceResponceDelegate> _delegate;
}

- (void) setDelegate:(id)delegate;
- (void) someTask;

@end

@implementation ServiceClass

- (void) setDelegate:(id)delegate
{
_delegate = delegate;
}

- (void) someTask
{
/*

   perform task

*/
if (!success)
{
[_delegate serviceDidFailWithRequestType:@”task failed”];
}
else
{
[_delegate serviceDidFinishedSucessfully:@”task success”];
}
}
@end

这是通过将委托设置为自身来调用服务类的主视图类。协议也在头类中实现。

@interface viewController: UIViewController <ServiceResponceDelegate>
{
ServiceClass* _service;
}

- (void) go;

@end

@implementation viewController

//
//some methods
//

- (void) go
{
_service = [[ServiceClass alloc] init];
[_service setDelegate:self];
[_service someTask];
}

就是这样,通过在这个类中实现委托方法,一旦操作/任务完成,控制权就会回来。

免责声明:这是如何创建委托 Swift 版本。

那么,代表们是什么? ...在软件开发中,有一般的可重用解决方案体系结构有助于解决给定上下文中常见的问题,可以说这些“模板”最为人所知的是设计模式。 委托是一种设计模式,允许一个对象在特定事件发生时将消息发送到另一个对象。 想象一下,对象A调用对象B来执行操作。一旦行动完成,对象A应该知道B已完成任务并采取必要的行动,这可以在代表的帮助下实现!

为了更好的解释,我将向您展示如何创建一个在类之间传递数据的自定义委托,在一个简单的应用程序中使用Swift,首先下载或克隆这个入门项目并运行它!

您可以看到一个包含两个类的应用程序, ViewController A ViewController B 。 B有两个视图可以随时更改 ViewController 的背景颜色,没什么太复杂的吧?现在让我们以一种简单的方式思考,当点击B类视图时,也可以改变A类的背景颜色。

问题是这些视图是B类的一部分而且不知道A类,所以我们需要找到一种在这两个类之间进行通信的方法,这就是委托发光的地方。 我将实施分为6个步骤,因此您可以在需要时将其用作备忘单。

步骤1:在ClassBVC文件中查找pragma mark步骤1并添加此

//MARK: step 1 Add Protocol here.
protocol ClassBVCDelegate: class {
func changeBackgroundColor(_ color: UIColor?)
}

第一步是创建协议,在这种情况下,我们将在B类中创建协议,在协议内部,您可以根据您的要求创建所需的多个功能实现。在这种情况下,我们只有一个简单的函数接受一个可选的 UIColor 作为参数。 在类名末尾添加单词 delegate ,在本例中为 ClassBVCDelegate ,这是一个很好的做法。

步骤2:在 ClassVBC 中查找pragma mark步骤2并添加此

//MARK: step 2 Create a delegate property here.
weak var delegate: ClassBVCDelegate?

这里我们只为类创建一个委托属性,该属性必须采用 protocol 类型,并且它应该是可选的。此外,您应该在属性之前添加weak关键字以避免保留周期和潜在的内存泄漏,如果您现在不知道这意味着什么,请记住添加此关键字。

步骤3:在 ClassBVC 中的handleTap 方法中查找编译指示标记步骤3并添加此

//MARK: step 3 Add the delegate method call here.
delegate?.changeBackgroundColor(tapGesture.view?.backgroundColor)

你应该知道的一件事,运行应用程序并点击任何视图,你将看不到任何新的行为,这是正确的,但我要指出的是,当委托是代表时它不会崩溃的应用程序调用,这是因为我们将其创建为可选值,这就是为什么即使委托不存在也不会崩溃的原因。现在让我们转到 ClassAVC 文件并制作它,委托。

步骤4:在 ClassAVC 中的handleTap方法中查找编译指示标记步骤4,然后将此类型添加到您的类类型旁边。

//MARK: step 4 conform the protocol here.
class ClassAVC: UIViewController, ClassBVCDelegate {
}

现在ClassAVC采用了 ClassBVCDelegate 协议,你可以看到你的编译器给你一个错误,上面写着“Type'ClassAVC不符合协议'ClassBVCDelegate',这只意味着你没有'然后使用协议的方法,想象当A类采用协议时就像签订B类合同一样,这个合同说“任何采用我的班级必须使用我的

答案实际已经回答,但我想给你一个“备忘单”。用于创建委托:

DELEGATE SCRIPT

CLASS A - Where delegate is calling function

@protocol <#Protocol Name#> <NSObject>

-(void)delegateMethod;

@end

@interface <#Some ViewController#> : <#UIViewController#> 

@property (nonatomic, assign) id <<#Protocol Name#>> delegate;

@end


@implementation <#Some ViewController#> 

-(void)someMethod {
    [self.delegate methodName];
}

@end




CLASS B - Where delegate is called 

@interface <#Other ViewController#> (<#Delegate Name#>) {}
@end

@implementation <#Other ViewController#> 

-(void)otherMethod {
    CLASSA *classA = [[CLASSA alloc] init];

    [classA setDelegate:self];
}

-delegateMethod() {

}

@end

ViewController.h

@protocol NameDelegate <NSObject>

-(void)delegateMEthod: (ArgType) arg;

@end

@property id <NameDelegate> delegate;

ViewController.m

[self.delegate delegateMEthod: argument];

MainViewController.m

ViewController viewController = [ViewController new];
viewController.delegate = self;

方法:

-(void)delegateMEthod: (ArgType) arg{
}

在我看来,为该委托方法创建单独的类,您可以使用所需的位置。

在我的Custom DropDownClass.h

typedef enum
{
 DDSTATE,
 DDCITY
}DropDownType;

@protocol DropDownListDelegate <NSObject>
@required
- (void)dropDownDidSelectItemWithString:(NSString*)itemString     DropDownType:(DropDownType)dropDownType;
@end
@interface DropDownViewController : UIViewController
{
 BOOL isFiltered;
}
@property (nonatomic, assign) DropDownType dropDownType;
@property (weak) id <DropDownListDelegate> delegate;
@property (strong, nonatomic) NSMutableArray *array1DropDown;
@property (strong, nonatomic) NSMutableArray *array2DropDown;

之后in.m文件创建包含对象的数组,

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
CGFloat rowHeight = 44.0f;
return rowHeight;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return isFiltered?[self.array1DropDown count]:[self.array2DropDown count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = @"TableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}

if (self.delegate) {
    if (self.dropDownType == DDCITY) {
        cell.textLabel.text = [self.array1DropDown objectAtIndex:indexPath.row];
    }
    else if (self.dropDownType == DDSTATE) {
        cell.textLabel.text = [self.array2DropDown objectAtIndex:indexPath.row];
    }
}
return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 [self dismissViewControllerAnimated:YES completion:^{
    if(self.delegate){
        if(self.dropDownType == DDCITY){
            [self.delegate dropDownDidSelectItemWithString:[self.array1DropDown objectAtIndex:indexPath.row] DropDownType:self.dropDownType];
        }
        else if (self.dropDownType == DDSTATE) {
            [self.delegate dropDownDidSelectItemWithString:[self.array2DropDown objectAtIndex:indexPath.row] DropDownType:self.dropDownType];
        }
    }
}];
}

这里都设置了自定义委托类。之后你可以在你想要的地方使用这个委托方法。例如......

之后我的另一个viewcontroller导入

创建用于调用委托方法的操作,如此

- (IBAction)dropDownBtn1Action:(id)sender {
DropDownViewController *vehicleModelDropView = [[DropDownViewController alloc]init];
vehicleModelDropView.dropDownType = DDCITY;
vehicleModelDropView.delegate = self;
[self presentViewController:vehicleModelDropView animated:YES completion:nil];
}

之后调用这样的委托方法

- (void)dropDownDidSelectItemWithString:(NSString *)itemString DropDownType:(DropDownType)dropDownType {
switch (dropDownType) {
    case DDCITY:{
        if(itemString.length > 0){
            //Here i am printing the selected row
            [self.dropDownBtn1 setTitle:itemString forState:UIControlStateNormal];
        }
    }
        break;
    case DDSTATE: {
        //Here i am printing the selected row
        [self.dropDownBtn2 setTitle:itemString forState:UIControlStateNormal];
    }

    default:
        break;
}
}

代表: - 创建

@protocol addToCartDelegate <NSObject>

-(void)addToCartAction:(ItemsModel *)itemsModel isAdded:(BOOL)added;

@end

发送并请指派代表查看您正在发送数据

[self.delegate addToCartAction:itemsModel isAdded:YES];
//1.
//Custom delegate 
@protocol TB_RemovedUserCellTag <NSObject>

-(void)didRemoveCellWithTag:(NSInteger)tag;

@end

//2.
//Create a weak reference in a class where you declared the delegate
@property(weak,nonatomic)id <TB_RemovedUserCellTag> removedCellTagDelegate;

//3. 
// use it in the class
  [self.removedCellTagDelegate didRemoveCellWithTag:self.tag];

//4. import the header file in the class where you want to conform to the protocol
@interface MyClassUsesDelegate ()<TB_RemovedUserCellTag>

@end

// 5。在类.m中实现该方法 - (无效)didRemoveCellWithTag:(NSInteger的)标签 {    NSLog @(&quot; Tag%d&quot;,tag);

}

让我们从一个例子开始,如果我们在网上购买产品,它会经历由不同团队处理的运输/交付等过程。因此,如果运输完成,运输团队应通知交付团队&amp;它应该是一对一的通信,因为广播这些信息对于其他人来说是开销,供应商可能只想将这些信息传递给所需的人。

因此,如果我们根据我们的应用程序考虑,活动可以是在线订单&amp;不同的团队可以像多个观点一样。

以下代码将ShippingView视为Shipping team&amp; DeliveryView作为交付团队:

//Declare the protocol with functions having info which needs to be communicated
protocol ShippingDelegate : class {
    func productShipped(productID : String)
}
//shippingView which shows shipping status of products
class ShippingView : UIView
{

    weak var delegate:ShippingDelegate?
    var productID : String

    @IBAction func checkShippingStatus(sender: UIButton)
    {
        // if product is shipped
        delegate?.productShipped(productID: productID)
    }
}
//Delivery view which shows delivery status & tracking info
class DeliveryView: UIView,ShippingDelegate
{
    func productShipped(productID : String)
    {
        // update status on view & perform delivery
    }
}

//Main page on app which has both views & shows updated info on product whole status
class ProductViewController : UIViewController
{
    var shippingView : ShippingView
    var deliveryView : DeliveryView

    override func viewDidLoad() {
        super.viewDidLoad()
        // as we want to update shipping info on delivery view, so assign delegate to delivery object
        // whenever shipping status gets updated it will call productShipped method in DeliveryView & update UI.
        shippingView.delegate = deliveryView
        //
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top