Detailed Explanation of Implementation Example of IOS Agent Mode
- 2021-07-18 09:09:16
- OfStack
Implementation of IOS Proxy Mode
In client development, notifications, proxies and block are often used to realize the association between various pages. Notification, in a straight "blind" way to achieve transmission. Agent, block
You can clearly know the relationship between various interfaces. Taking agency as an example, the general practice is as follows:
DesViewController *des = [[DesViewController alloc] init];des.delegate = self;[self.navigationController pushViewController:des animated:YES];
In this case, there is a definite relationship between the two interfaces, for example, jumping from A interface to B interface or a view is a part between A controllers. However, if there is no contact, how to deal with it? For example, A interface needs to display different data according to user login status, or display different interface conditions:
Actual combat:
Idea: Create a management class processing, set the corresponding proxy method, and then add or delete the corresponding proxy method when needed.
Core code:
. h file
//// RSLoginService.h// iOSDelegate//// Created by admin on 2016/11/6.// Copyright © 2016 Year Reading. All rights reserved.
//#import <Foundation/Foundation.h>@protocol UserLoginStatusDelegate <NSObject>
- (void)userDidLoginIn;
- (void)userWillLoginOut;
@end@interface RSLoginService : NSObject+ (instancetype)sharedInstance;
@property (nonatomic, strong) NSMutableSet *delegates;
- (void)onWillLoginOut;
- (void)onDidLoginIn;
- (void)addDelegate:(id<UserLoginStatusDelegate>) delegate;
- (void)removeDelegate:(id<UserLoginStatusDelegate>) delegate;@end
. m file
//// RSLoginService.m// iOSDelegate//// Created by admin on 2016/11/6.
// Copyright © 2016 Year Reading. All rights reserved.
//#import "RSLoginService.h"@implementation
RSLoginService+ (instancetype)sharedInstance{ static id instance; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{
instance = [[RSLoginService alloc] init]; }); return instance;}- (void)onWillLoginOut{
// do something you need to do before Login out
[self.delegates makeObjectsPerformSelector:@selector(userWillLoginOut)];}- (void)onDidLoginIn{
// do something you need to do after Login In
[self.delegates makeObjectsPerformSelector:@selector(userDidLoginIn)];}-
(void)addDelegate:(id<UserLoginStatusDelegate>) delegate{ if (![self.delegates containsObject:delegate])
{ [self.delegates addObject:delegate]; }
}- (void)removeDelegate:(id<UserLoginStatusDelegate>)
delegate{ if (![self.delegates containsObject:delegate]) {
[self.delegates removeObject:delegate]; }}- (NSMutableSet *)delegates{ if (!_delegates) { _delegates = [NSMutableSet set]; } return _delegates;}@end
Thank you for reading, hope to help everyone, thank you for your support to this site!