iOS 代理方式的實作
在客戶端開發中,經常會用到通知、代理、block 來實現各頁面之間的關聯。通知以一種全程「盲發」的方式傳遞訊息,而代理與 block 則能明確掌握各界面之間的關聯關係。以代理為例,一般做法如下:
DesViewController *des = [[DesViewController alloc] init];des.delegate = self;[self.navigationController pushViewController:des animated:YES];
這種情況下,兩個界面之間通常存在一定的關係,例如從 A 界面跳轉到 B 界面,或者 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
感謝閱讀,希望能幫助到你,謝謝你對本站的支持!