I\'m having issues understanding the concept of outlets how the iPhone deals with events. Help! Delegates confuse me too. Would someone care to explain, please?
Outlets (in Interface Builder) are member variables in a class where objects in the designer are assigned when they are loaded at runtime. The IBOutlet
macro (which is an empty #define
) signals Interface Builder to recognise it as an outlet to show in the designer.
For example, if I drag out a button, then connect it to the aButton
outlet (defined in my interface .h file), the loading of the NIB file at runtime will assign aButton
the pointer to that UIButton
instantiated by the NIB.
@interface MyViewController : UIViewController {
UIButton *aButton;
}
@property(nonatomic, retain) IBOutlet UIButton *aButton;
@end
Then in the implementation:
@implementation MyViewController
@synthesize aButton; // Generate -aButton and -setAButton: messages
-(void)viewDidAppear {
[aButton setText:@"Do Not Push. No, seriously!"];
}
@end
This eliminates the need to write code to instantiate and assign the GUI objects at runtime.
As for Delegates, they are event receiving objects used by another object (usually a generalised API class such as a table view). There's nothing inherently special about them. It's more of a design pattern. The delegate class may define several of the expected messages such as:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
...and the API object calls this message on the delegate when it wants to notify it of the event. For example:
-(void)update:(double)time {
if (completed) {
[delegate process:self didComplete:totalTimeTaken];
}
}
And the delegate defines the message:
-(void)process:(Process *)process didComplete:(double)totalTimeTaken {
NSString *log = [NSString stringWithFormat:@"Process completed in %2.2f seconds.", totalTimeTaken];
NSLog(log);
}
Such use might be:
Process *proc = [Process new];
[proc setDelegate:taskLogger];
[proc performTask:someTask];
// Output:
// "Process completed in 21.23 seconds."