代表们如何工作并将工作流程委托给客户-c

时间:2015-03-22 09:15:37

标签: ios objective-c delegates

我是Objective-c的新手。我正在学习目标-c。你能不能让我知道这段代码是如何工作的,你能否帮助理解代表们在objective-c中的工作流程

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

为标签创建IBOutlet并将其命名为myLabel,并按照以下代码更新代码,以采用ViewController.h中的SampleProtocolDelegate

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

@interface ViewController : UIViewController<SampleProtocolDelegate>
{
    IBOutlet UILabel *myLabel;
}
@end

和更新的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

2 个答案:

答案 0 :(得分:5)

首先,我要指出,当您使用@property声明属性时,不需要使用下划线前缀创建单独的实例变量。您可以使用self.delegate访问此媒体资源,并自动为您创建_delegate。由于_delegate已使用@property创建,因此您可以取出重复声明。

其次,您可以将<SampleProtocolDelegate>移动到属性声明,还应将其设置为弱以避免保留周期。见:Why use weak pointer for delegation?。所以你的界面最终看起来像这样:

@interface SampleProtocol : NSObject

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

-(void)startSampleProcess;

@end

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

答案 1 :(得分:4)

委托是开发人员工具库中的一个强大工具,我认为委托是一种简洁的连接对象并帮助他们与其他人交流的方式。换句话说,委托是Objective-C对象的约会服务。让我们说我们有两个对象,Brain和Beer Bottle,Brain是我们用来管理整个Body应用程序的对象,它处理所有重要的事情诸如大便,吃,喝,睡觉等任务。啤酒瓶附着在身体上,但它并不知道大脑在想什么,同样,大脑也不知道啤酒瓶在想什么。

大脑正在使用啤酒瓶的属性来满足自己在看电视时的需求,但问题是大脑被电视分散注意力,以至于当啤酒是啤酒时,它无法注意要用完了。这一切都可能在灾难中结束,Brain需要知道什么时候啤酒是空的,这样它就会将身体送到冰箱并初始化另一个啤酒瓶实例。

大脑可以使用饮料功能降低啤酒瓶液体变量,但一旦液体达到0,脑需要了解它,这是代表们采取行动的地方,我们可以使用Beer Bottle Delegate。大脑可以听取啤酒瓶代表告诉大脑瓶子是空的,我们只需告诉Brain听啤酒瓶告诉它的代表是空的,Brain可以对它作出反应。这个经过深思熟虑和图解说明的图表显示了所有这一切 enter image description here