Proxy mode is often used to solve a problem like this: we open Interface B through interface A, but in the course of the application, interface B sometimes needs to contact a actively, such as when a button is clicked. A better way is to make a a agent of B, so that B can send a message to a when needed.
One of the benefits of proxy mode is that B actually doesn't need to know anything about a, as long as you know that a is your agent. In this mode, B is still independent from a, which achieves loose coupling.
Object A is a proxy for object B, and object B needs to send a message to a, setting the method in four steps:
1. Define a protocol proxy protocol in the. H of object B, and declare the property variables of a protocol
2. Let object B send a message to proxy object A when appropriate, such as when the button is triggered.
3. Let object a comply with the agent agreement
4, notify the object B, now a is its agent
Steps:
1. Define proxy protocols and attribute variables in B.h
1 /*****b.h*****/2 3 @protocolBdelegate<nsobject>4 5- (void) Degegatemethod: (instancetype) instance;6 7 @end8 9 @interfaceBTen One@property (weak,nonatomic)ID<BDelegate>Delegate; A - @end
2, in B.M to implement the method of B to send a message, to press the Done button as an example:
1 /*****b.m******/2 3 #import "B.h"4 5 @interfaceB ()6 7 @end8 9 @implementationBTen One-(Ibaction) Done: (ID) sender{ A[Self.DelegateDelegatemethod:instance]; - } - the@end
3, let a comply with the agency agreement, add a angle bracket in A.h's @interface statement
1 /* ****a.h**** */ 2 3 @interface A<bdelegate>45@end
4, notify the object B,a has become its agent. Implementing the Proxy method in the A.M. can
1 /*****a.m*****/2 3 #import "A.h"4 5 @interfaceA ()6 7 @end8 9 @implementationATen One- (void) Delegateidentifiermethod: (B *) b{ A //Do something; -B.Delegate=self;//identify the delegate of B is A - } the -- (void) Delegatemethod: (instancetype) instance{ - //Do something - } + - @end
It is important to note that the proxy method declared in B.h Delegatemethod needs to be implemented in A.M., otherwise an error will be made.
iOS Proxy Mode setting method