目标C术语:网点和代表

Mos*_*she 8 iphone delegates objective-c cocoa-design-patterns outlet

我在理解iPhone如何处理事件的出口概念方面遇到了问题.救命!代表们也让我感到困惑.有人会关心解释吗?

Nic*_*ord 19

Outlets(在Interface Builder中)是类中的成员变量,其中设计器中的对象在运行时加载时被分配.的IBOutlet宏(这是一个空的#define)信号界面生成器,以将其识别为出口在设计来显示.

例如,如果我拖出一个按钮,然后将其连接到aButton插座(在我的接口.h文件中定义),则在运行时加载NIB文件将指定aButton指向UIButton由NIB实例化的指针.

@interface MyViewController : UIViewController {
    UIButton *aButton;
}

@property(nonatomic, retain) IBOutlet UIButton *aButton;

@end
Run Code Online (Sandbox Code Playgroud)

然后在实施中:

@implementation MyViewController

@synthesize aButton; // Generate -aButton and -setAButton: messages

-(void)viewDidAppear {
    [aButton setText:@"Do Not Push. No, seriously!"];
}

@end
Run Code Online (Sandbox Code Playgroud)

这消除了编写代码以在运行时实例化和分配GUI对象的需要.


至于Delegates,它们是接收另一个对象使用的对象的事件(通常是一个通用的API类,如表视图).关于他们没有任何内在的特殊之处.它更像是一种设计模式.委托类可以定义几个预期的消息,例如:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
Run Code Online (Sandbox Code Playgroud)

...当API对象想要通知事件时,它会在委托上调用此消息.例如:

-(void)update:(double)time {
    if (completed) {
        [delegate process:self didComplete:totalTimeTaken];
    }
}
Run Code Online (Sandbox Code Playgroud)

委托定义了消息:

-(void)process:(Process *)process didComplete:(double)totalTimeTaken {
    NSString *log = [NSString stringWithFormat:@"Process completed in %2.2f seconds.", totalTimeTaken];
    NSLog(log);
}
Run Code Online (Sandbox Code Playgroud)

这种用途可能是:

Process *proc = [Process new];
[proc setDelegate:taskLogger];
[proc performTask:someTask];

// Output:
// "Process completed in 21.23 seconds."
Run Code Online (Sandbox Code Playgroud)


pok*_*tad 9

委托是另一个对象可以转发消息的对象.换句话说,就像你的妈妈告诉你打扫你的房间,然后你把它当作你的小弟弟一样.你的小兄弟知道如何完成这项工作(因为你懒得学习),所以他为你做了.

  • 妈妈为什么不直接问弟弟呢? (3认同)