IOS 代理方式实现
在客户端开发中,经常用到通知、代理、block来实现各个页面之间关联。通知,以一直“盲”的方式实现传递。 代理、block
可以很明确的知道各个界面之间的关联关系。以代理为例,一般的做法如下 :
DesViewController *des = [[DesViewController alloc] init];des.delegate = self;[self.navigationController pushViewController:des animated:YES];
这种情况下,一般两个界面是有一定的关系的,例如:从A界面跳转到B界面或者a的视图是A控制器之间一部分。但是,如果没有联系的怎么处理呢,例如: A界面需要根据用户登录状态来展示不同的数据,或者展示不同的界面情况:
实战:
思路: 创建一个管理类类处理,设置好对应的代理方法,然后再需要的时候,添加 或者 删除对应的代理方法即可。
核心代码:
.h文件
1
2
3
4
5
6
7
8
9
10
|
//// RSLoginService.h// iOSDelegate//// Created by admin on 2016/11/6.// Copyright © 2016年 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文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
//// RSLoginService.m// iOSDelegate//// Created by admin on 2016/11/6.
// Copyright © 2016年 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
|
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!