最近在集成环信SDK,查看其API的时候,发现了一种对于我比较新的一种写法。
需求
在我们做badge显示的时候,需要在多个地方展示这个数字。并且也可以在多个地方修改这个数字,那么我们怎么让这些页面进行同步呢?
解决方法:1
在我们设计到页面都监听Notification.并实现其的监听方法。当数字改变的时候postNotification: 来达到各个页面同时修改的数字。
解决方法:2
代码如下:
TranbTimeLineBadgeUtils.h/.m文件
实现逻辑:定义一个全局的工具类。把badge的计算和事件获取都在这个类中实现。
并在所需要的页面中执行下面代码,把当前页面加入到工具类的监听对象集。
#pragma mark - 注册badge的回调事件
-(void)registerBadgeNotifications
{
[self unregisterBadgeNotifications];
[[TranbTimeLineBadgeUtils sharedInstance] addDelegate:self];
}
-(void)unregisterBadgeNotifications
{
[[TranbTimeLineBadgeUtils sharedInstance] removeDelegate:self];
}
#pragma mark - 消息中心消息计数
- (void)didUpdateMessageCenterTotalCount:(NSInteger)nCount
{
//处理页面的展示
}
工具类源码如下:
移除了逻辑相关类。只保留了相关结构。
@protocol TranbTimeLineBadgeDelegate;
@interface TranbTimeLineBadgeUtils : NSObject
//初始化方法
+ (instancetype)sharedInstance;
/**
* 注册一个监听对象到监听列表中
*
* @param delegate 需要注册的监听对象
*
* @since 1.640
*/
-(void)addDelegate:(id<TranbTimeLineBadgeDelegate>) delegate;
/**
* 从监听列表中移除一个监听对象
*
* @param delegate 需要移除的监听对象
*
* @since 1.640
*/
-(void)removeDelegate:(id<TranbTimeLineBadgeDelegate>) delegate;
@end
/**
* 首页消息中心的回调方法
*
* @since 1.640
*/
@protocol TranbTimeLineBadgeDelegate <NSObject>
/**
* 更新消息中心消息计数(包含私信 和 交换名片)
*
* @param nCount 返回新的总数量
*
* @since 1.640
*/
- (void)didUpdateMessageCenterTotalCount:(NSInteger)nCount;
@end
#import "TranbTimeLineBadgeUtils.h"
@interface TranbTimeLineBadgeUtils ()
{
NSPointerArray* _delegates; // the array of observing delegates
}
@end
@implementation TranbTimeLineBadgeUtils
+ (instancetype)sharedInstance
{
static TranbTimeLineBadgeUtils *badgeUtils = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
badgeUtils = [[TranbTimeLineBadgeUtils alloc] init];
});
return badgeUtils;
}
-(id)init
{
self = [super init];
if (self) {
_delegates = [NSPointerArray weakObjectsPointerArray];
//添加自定义的监听
}
return self;
}
-(void)dealloc
{
}
-(void)addDelegate:(id<TranbTimeLineBadgeDelegate>) delegate
{
__weak typeof(id<TranbTimeLineBadgeDelegate>) weakDelegate = delegate;
[_delegates addPointer:(__bridge void *)(weakDelegate)];
}
-(void)removeDelegate:(id<TranbTimeLineBadgeDelegate>) delegate
{
int rIndex = -1;
for (int index = 0; index < [_delegates count]; index++) {
id<TranbTimeLineBadgeDelegate> pDelegate = [_delegates pointerAtIndex:index];
if (pDelegate == nil) {
rIndex = index;
break;
}
}
if (rIndex > -1) {
[_delegates removePointerAtIndex:rIndex];
}
}
@end







网友评论