Application 1: data transfer between classes

  • Subordinate -> superior data transfer

Using proxies is a good way to avoid the problem of interdependencies between controllers (importing each other’s headers). For data transfer between the upper and lower controllers, I can pass data to whoever becomes my agent.

Using the step

1. Declare the agent

Define a protocol; Define proxy methods; Set the proxy properties. Declare in.h of the class:

// Introduce the class name @class PDmyHeadView; @protocol PDmyHeadViewDelegate <NSObject> Class name +Delegate) -(void)clickHeadButton (PDmyHeadView *)headView headButton (UIButton *)headImgBtn; @end@interface PDmyHeadView: UIView @property(nonatomic,weak) id<PDmyHeadViewDelegate> delegate; // Declare the proxy attribute @endCopy the code

PS: Once freed, the delegate must be nil, otherwise it will be a wild pointer, causing a memory leak, which is why we declare the delegate as weak.

2. Proxy invocation

In a triggering method (such as a click), the agent owner determines whether its agent implements the agent method defined above, and if so, executes the agent method.

-(void)clickHeader:(UIButton *)headImgBtn{ if([self.delegate respondsToSelector:@selector(clickHeadButton:headButton:)]){ [self.delegate clickHeadButton:self headButton:headImgBtn];  // let the proxy call the proxy method}}Copy the code

Become a proxy and implement proxy methods

// create self.myHeadView = [[PDmyHeadView alloc] init]; self.myHeadView.delegate = self; . -(void)clickHeadButton:(PDmyHeadView *) headview headButton:(UIButton *)headImgBtn{ NSLog("--%zd",headImgBtn.tag); // get data}Copy the code

supplement

You can only communicate one to one – let’s say you have class A, class B, class C – class C is A CDelegate, and when you click on A button for class C, the corresponding protocol, the output says – class A and class B both implement methods – the action is to jump from class A to class B, jump from class B to class C, click on A button for class C, and only class B responds.