iphone - Objective-C 术语 : outlets & delegates

标签 iphone objective-c delegates cocoa-design-patterns outlet

我在理解 iPhone 如何处理事件的 socket 概念时遇到了问题。帮助!委托(delegate)们也让我感到困惑。请有人愿意解释一下吗?

最佳答案

Outlets(在 Interface Builder 中)是类中的成员变量,设计器中的对象在运行时加载时会在其中分配。 IBOutlet 宏(它是一个空的 #define)指示 Interface Builder 将其识别为在设计器中显示的 socket 。

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

@interface MyViewController : UIViewController {
    UIButton *aButton;
}

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

@end

然后在实现中:

@implementation MyViewController

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

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

@end

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


至于Delegates,它们是另一个对象(通常是通用的API类,如 TableView )使用的事件接收对象。它们本身并没有什么特别之处。它更像是一种设计模式。委托(delegate)类可以定义几个预期的消息,例如:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

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

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

委托(delegate)定义消息:

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

这样的用途可能是:

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

// Output:
// "Process completed in 21.23 seconds."

关于iphone - Objective-C 术语 : outlets & delegates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2068625/

相关文章:

ios - 它是如何运作的

objective-c - 显示下一个和上一个详细信息 UIView,而不返回父 UITableView

ios - 如何将标题和自定义图像添加到 MKMapView 中的特定位置图钉?

iphone - 访问委托(delegate)中的局部变量的正确方法是什么?

iPhone - 如何在矩形中间绘制文本

iphone - 如何在 XCode 中设置 SVN 存储库?

iphone - 如何从导航栏创建下拉菜单(iOS)

ios - 如何使用OCMock测试UIButton的setTitle

cocoa - NSTextField 和 NSTextView : Overlapping Delegate Methods

c# - 如何在 .Net 中实现 "convert using this function"自定义属性?