如何委托工作和委托工作stream程在Objective-C

我是Objective-C的新手。 我正在学习Objective-C。 你会不会让我知道这个代码是如何工作的,以及你是否会帮助理解委托人在Objective-C中的工作stream程

SampleProtocol.h #import <Foundation/Foundation.h> @protocol SampleProtocolDelegate <NSObject> @required - (void) processCompleted; @end @interface SampleProtocol : NSObject { id <SampleProtocolDelegate> _delegate; } @property (nonatomic,strong) id delegate; -(void)startSampleProcess; @end 

我在下面的代码中添加SampleProtocol.m

 #import "SampleProtocol.h" @implementation SampleProtocol -(void)startSampleProcess{ [NSTimer scheduledTimerWithTimeInterval:3.0 target:self.delegate selector:@selector(processCompleted) userInfo:nil repeats:NO]; } @end 

为标签创build一个IBOutlet并将其命名为myLabel,并按照以下方式更新代码以在ViewController.h采用SampleProtocolDelegate

 #import <UIKit/UIKit.h> #import "SampleProtocol.h" @interface ViewController : UIViewController<SampleProtocolDelegate> { IBOutlet UILabel *myLabel; } @end 

和Updated ViewController.m文件如下

 #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; SampleProtocol *sampleProtocol = [[SampleProtocol alloc]init]; sampleProtocol.delegate = self; [myLabel setText:@"Processing..."]; [sampleProtocol startSampleProcess]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } #pragma mark - Sample protocol delegate -(void)processCompleted{ [myLabel setText:@"Process Completed"]; } @end 

首先让我指出,当你使用@property来声明一个属性时,你不需要创build一个带有下划线前缀的单独的实例variables。 你可以使用self.delegate访问这个属性,它也会为你自动创build_delegate 。 由于_delegate已经使用_delegate创build,所以可以取出重复的声明。

其次,您可以将<SampleProtocolDelegate>移动到属性声明中,也应将其设置为较弱以避免保留周期。 请参阅: 为什么使用弱指针进行授权? 。 所以你的界面最终会看起来像这样:

 @interface SampleProtocol : NSObject @property (nonatomic, weak) id <SampleProtocolDelegate> delegate; -(void)startSampleProcess; @end 

通过在“id”和“delegate”之间放置<SampleProtocolDelegate> ,只有符合SampleProtocolDelegate的对象才能将自己设置为对象的委托(意味着符合此协议的任何对象)。 而且SampleProtocol对象可以安全地假定它可以在其代理上调用协议方法。

代表团是开发人员库中的一个强大的工具,我将代表团看作是连接对象并帮助他们与其他对象进行通信的干净而简单的方式。 换句话说,代表团是Objective-C对象的约会服务。比方说,我们有两个对象,Brain和Beer Bottle,Brain是我们用来pipe理整个Body应用程序的对象,它处理所有重要的任务, ,吃,喝,睡等。啤酒瓶附着在身体上,但不知道脑子在想什么,脑子也不知道啤酒瓶在想什么。

大脑在看电视的时候用啤酒瓶的属性来满足自己的需求,但问题是大脑被电视分心,以至于啤酒即将用完时,不能注意。 这一切都可能以灾难结束,大脑需要知道啤酒何时是空的,以便它将身体送到冰箱,并初始化另一个啤酒瓶。

大脑可以使用饮料function降低啤酒瓶液体variables,但是一旦液体达到0,大脑需要了解它,这是代表们开始行动的地方,我们可以使用Beer Bottle Delegate 。 大脑可以听取啤酒瓶代表告诉大脑瓶子是空的,我们只需要告诉大脑听取啤酒瓶,告诉它代表是空的,大脑可以对它做出反应。 这个深思熟虑的插图显示了所有这些在行动 在这里输入图像说明