Protocol-the protocol is used to follow the protocol, and the implementation method required by the protocol must be implemented.
Delegate-delegation, as its name implies, is to entrust others to handle affairs, that is, when one thing happens, it will not be handled by others.
If A view contains B view and B view needs to be modified on the view Interface, delegation is required.
Several steps are required
1. First define an agreement
2. Methods of a view Implementation Protocol
3. B view sets a delegate variable.
4. Set the delegate variable of B view to a view, which means that B view delegates a view to do things.
5. After an event occurs, use the delegate variable to call the Protocol method in a view.
The steps below are described as follows:
1. First define a protocol
@protocol PlayerDetailDelegate <NSObject>-(void) updatePlayer:(Player *)player;@end
This is a formal way to define the protocol, and also an informal Protocol. Its essence is Category, which extends the existing class methods.
2. Methods of a view Implementation Protocol
First, add the implementation protocol to the header file.
@interface PlayersViewController : UITableViewController<PlayerDetailDelegate>{ Player *selectedPlayer;}@property(nonatomic,strong) NSMutableArray *players;@end
Then implement the methods in the Protocol in the implementation file
-(void) updatePlayer:(Player *)player{ selectedPlayer = player; NSLog(@"name%@",selectedPlayer.name);}
3. Set a delegate variable in B view.
@interface PlayerDetailViewController : UIViewController{ id<PlayerDetailDelegate> _playerDelegate;}@property(nonatomic,strong) IBOutlet UITextView *detailView;@property(nonatomic,strong) Player *player;@property(nonatomic,strong) id<PlayerDetailDelegate> _playerDelegate;- (IBAction)buttonPressed:(id)sender;@end
Call the delegate object in a proper place
-(IBAction) buttonPressed :( id) sender {if (_ playerDelegate! = Nil & [_ playerDelegate respondsToSelector: @ selector (updatePlayer :)]) {self. player. name = self. detailView. text; [_ playerDelegate updatePlayer: self. player];} NSLog (@ "Run! ");}
4. Set the delegate variable of B view to a view, which means that B view delegates a view to do things.
5. After an event occurs, use the delegate variable to call the Protocol method in a view.