我在理解 iPhone 如何处理事件的网点概念时遇到问题。帮助!代表们也让我感到困惑。有人愿意解释一下吗?
2 回答
Outlets(在 Interface Builder 中)是类中的成员变量,其中设计器中的对象在运行时加载时被分配。IBOutlet
宏(它是一个空的)#define
指示 Interface Builder 将其识别为在设计器中显示的出口。
例如,如果我拖出一个按钮,然后将其连接到aButton
插座(在我的接口 .h 文件中定义),则在运行时加载 NIB 文件会将aButton
指针分配给UIButton
由 NIB 实例化的指针。
@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 类,例如表视图)。它们本质上没有什么特别之处。它更像是一种设计模式。委托类可以定义一些预期的消息,例如:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
...并且当 API 对象想要通知该事件时,它会在委托上调用此消息。例如:
-(void)update:(double)time {
if (completed) {
[delegate process:self didComplete:totalTimeTaken];
}
}
委托定义了消息:
-(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."
A delegate is a object that another object can forward messages to. In other words, it's like when your mom told you to clean your room and you pawned it off on your little brother. Your little bro knows how to do the job (since you were too lazy to ever learn) and so he does it for you.