Objective C terminology: outlets & delegates

后端 未结 2 1918
别那么骄傲
别那么骄傲 2021-02-06 07:13

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?

相关标签:
2条回答
  • 2021-02-06 07:35

    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."
    
    0 讨论(0)
  • 2021-02-06 07:43

    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.

    0 讨论(0)
提交回复
热议问题