IOS 代理方式實現
在客戶端開發中,經常用到通知、代理、block來實現各個頁面之間關聯。通知,以一直“盲”的方式實現傳遞。 代理、block
可以很明確的知道各個界面之間的關聯關系。以代理為例,一般的做法如下 :
DesViewController *des = [[DesViewController alloc] init];des.delegate = self;[self.navigationController pushViewController:des animated:YES];
這種情況下,一般兩個界面是有一定的關系的,例如:從A界面跳轉到B界面或者a的視圖是A控制器之間一部分。但是,如果沒有聯系的怎麼處理呢,例如: A界面需要根據用戶登錄狀態來展示不同的數據,或者展示不同的界面情況:
實戰:
思路: 創建一個管理類類處理,設置好對應的代理方法,然後再需要的時候,添加 或者 刪除對應的代理方法即可。
核心代碼:
.h文件
//// 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文件
//// 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
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!