What exactly does delegate do in xcode ios project?

前端 未结 3 549
难免孤独
难免孤独 2020-11-27 04:37

I have just been learning iPhone apps development but I have a hard time in understanding what delegate actually means? Can anyone tell me with example what it does and how

3条回答
  •  伪装坚强ぢ
    2020-11-27 05:32

    A delegate is an object that another class can pass messages to. In practice delegate classes have to conform to a delegate protocol.

    For instance we will take a subclass of a table view controller. This is a delegate for your table view. First you define that it is a table view delegate by doing this:

    MyTableViewController : UITableViewController 
    

    This says that class MyTableViewController is a subclass of UITableViewController and CONFORMS to the UITableViewDelegate protocol.

    Setting [tableView setDelegate:self] (or defining it as such in IB) then passes the self object to the tableview in order for the tableview to send messages to it.

    The main message it sends is the didSelectRowAtIndexPath message which tells your class that the user has pressed a table view cell.

    So the object that takes the click event (the table view) passes on the message that the cell has been clicked to the delegate object (which in this case is your MyTableViewController object).

    Delegate protocols exist so that you can make sure that the delegate object has the necessary methods to deal with your messages. Methods in a delegate protocol can be @optional or enforced. Any methods that are optional don't have to be defined. In your MyTableViewController class the method didSelectRowAtIndexPath is optional - you don't have to have it. If the table view doesn't find the method it just won't call it.

    However the cellForRowAtIndexPath is necessary and without it your app won't compile.

    I hope this helps and is straightforwards for you. If you need any more info let me know.

提交回复
热议问题