倔强青铜:如何避免写出丑陋的通知代码

2023-11-22 14:10

本文主要是介绍倔强青铜:如何避免写出丑陋的通知代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

640?wx_fmt=png

大概从入门 iOS 的青铜段位我们就开始使用 NotificationCenter 实现跨层一对多的消息传递,具体实现代码大概如下:

//发送通知	
let info = ["newsId": 12345,"comment": Comment.init(user_id: 1, content: "laofeng talk: exp")] as [String : Any]	
NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "com.notification.comment"), object: nil, userInfo: info)	//接收通知	
notificationHolder1 = NotificationCenter.default.addObserver(forName: NSNotification.Name.init(rawValue: "com.notification.comment"), object: nil, queue: nil) { (notification) in	guard let userInfo = notification.userInfo as? [String:Any] else { return }	guard let newsId = userInfo["newsId"] as? Int else { return }	guard let comment = userInfo["comment"] as? Int else { return }	print(newsId)	print(comment)	
}

在开发中是否依然倔强的坚持类似上面的写法?如果是的话请继续阅读,其实上面的代码存在一些问题:

  1. 在每个需要收发通知的地方都需要 NSNotification.Name 如果有某个地方通知名写错,则会出现无法接收通知的问题

  2. 在每个需要接收通知的地方都需要解析 userInfo ,如果硬编码key不正确则,解析错误

这样会导致每当我们需要 post 或 observer 通知的时候,都需要重一次写上面的代码。假如需要增加或者删除一个 userInfo 传递的参数,那就需要 CMD + F 找到每一处发送和接收通知的地方进行修改,这样维护起来就非常痛苦,那么是否有更优雅的方式可以组织代码呢?

 类型化通知

在 objc.io talk 教程 S01E27-typed-notifications-part中介绍了Typed-Notifications, 使用强类型化通知在收发端只需如下的优雅写法即可拿到已经处理好的数据。

//发送通知	
CommentChangeNotification.init(newsId: 12345, comment: Comment.init(user_id: 1, content: "laofeng talk: TypedNotification")).post()	
//接收通知	
notificationHolder = CommentChangeNotification.registerObserver { (info) in	print(info.newsId)	print(info.comment)	
}

而通过定义 CommentChangeNotification 实现实现 TypedNotification 协议,通知名、通知数据处理集中在一处,这样在业务中监听通知的地方就不需要每个地方都解析 userInfo 数据,即使后期需要增加删除参数也可在这里集中处理。

// 评论改变通知	
struct CommentChangeNotification: TypedNotification {	//通知名	static var name: Notification.Name {	return "com.notification.comment"	}	// 通知传递的 userInfo 数据	let newsId: Int	let comment: Comment	var userInfo: [AnyHashable: Any]? {	return ["newsId": newsId,	"comment": comment	]	}	init(_ notification: Notification) {	newsId = notification.userInfo?["newsId"] as! Int	comment = notification.userInfo?["comment"] as! Comment	}	init( newsId: Int, comment: Comment) {	self.newsId = newsId	self.comment = comment	}	
}

 TypedNotification 如何实现

1、定义通知描述协议包含 name、userInfo、object。

protocol NotificationDescriptor {	static var name: Notification.Name { get }	var userInfo: [AnyHashable: Any]? { get }	var object: Any? { get }	
}	
extension NotificationDescriptor {	var userInfo: [AnyHashable: Any]? {	return nil	}	var object: Any? {	return nil	}	
}	
extension NotificationDescriptor {	public func post(on center: NotificationCenter = NotificationCenter.default) {	print(Self.name)	center.post(name: Self.name, object: object, userInfo: userInfo)	}	
}

2、定义通知数据解析协议,在 observer 的 block 中解析 userInfo。

protocol NotificationDecodable {	init(_ notification: Notification)	
}	
extension NotificationDecodable {	@discardableResult	public static func observer(on center: NotificationCenter = NotificationCenter.default ,	for aName: Notification.Name,	using block: @escaping (Self) -> Swift.Void) -> NotificationToken {	let token = center.addObserver(forName: aName, object: nil, queue: nil, using: {	block(Self.init($0))	})	print(aName)	return NotificationToken.init(token, center: center)	}	
}

3、 定义类型化协议并实现通知注册方法。

typealias NotificationProtocol = NotificationDescriptor & NotificationDecodable	
protocol TypedNotification : NotificationProtocol {	static func registerObserver(using block: @escaping (Self) -> Swift.Void) -> NotificationToken	
}	
extension TypedNotification {	static func registerObserver(using block: @escaping (Self) -> Swift.Void) -> NotificationToken {	return self.observer(on: NotificationCenter.default, for: Self.name, using: block)	}	
}

4、实现一个新通知只需实现 TypedNotification 即可,NotificationToken 类似于NSKeyValueObservation, 并不需要手动去移除通知,只需管理 NotificationToken 的生命周期就可以了。

总结

类型化通知不管是 ObjC 还是 Swift 都可以实现,本文以 Swift 为例,文中源码可点击 阅读原文 或 推荐阅读 中查看。使用类型化通知可避免分散在各处的 Notification 数据处理,也让通知数据处理更安全且易于维护。其实个人认为通知虽然好用,但不宜滥用,应避免业务代码中通知满天飞的尴尬局面。最后思考个问题比如在 VC 中 有个 ProductView,ProductView中包含 TableView ,TableView 中 Cell 上有一个点击购买事件,这个事件需要将购买信息传递至 Cell、ProductView、VC 那么你会如何分发这个事件呢?

推荐阅读:

  1. https://github.com/GesanTung/iOSTips/tree/master/02-TypedNotifications

  2.  最佳实践:重构AppDelegate

  3.  https://talk.objc.io/episodes/S01E27-typed-notifications-part-1

  4.  重构:《重构改善既有代码的设计》

  5. 今天继续兑现吹过的牛逼

640?wx_fmt=png

这篇关于倔强青铜:如何避免写出丑陋的通知代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/410689

相关文章

Python如何去除图片干扰代码示例

《Python如何去除图片干扰代码示例》图片降噪是一个广泛应用于图像处理的技术,可以提高图像质量和相关应用的效果,:本文主要介绍Python如何去除图片干扰的相关资料,文中通过代码介绍的非常详细,... 目录一、噪声去除1. 高斯噪声(像素值正态分布扰动)2. 椒盐噪声(随机黑白像素点)3. 复杂噪声(如伪

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Java中Map.Entry()含义及方法使用代码

《Java中Map.Entry()含义及方法使用代码》:本文主要介绍Java中Map.Entry()含义及方法使用的相关资料,Map.Entry是Java中Map的静态内部接口,用于表示键值对,其... 目录前言 Map.Entry作用核心方法常见使用场景1. 遍历 Map 的所有键值对2. 直接修改 Ma

深入解析 Java Future 类及代码示例

《深入解析JavaFuture类及代码示例》JavaFuture是java.util.concurrent包中用于表示异步计算结果的核心接口,下面给大家介绍JavaFuture类及实例代码,感兴... 目录一、Future 类概述二、核心工作机制代码示例执行流程2. 状态机模型3. 核心方法解析行为总结:三

python获取cmd环境变量值的实现代码

《python获取cmd环境变量值的实现代码》:本文主要介绍在Python中获取命令行(cmd)环境变量的值,可以使用标准库中的os模块,需要的朋友可以参考下... 前言全局说明在执行py过程中,总要使用到系统环境变量一、说明1.1 环境:Windows 11 家庭版 24H2 26100.4061

pandas实现数据concat拼接的示例代码

《pandas实现数据concat拼接的示例代码》pandas.concat用于合并DataFrame或Series,本文主要介绍了pandas实现数据concat拼接的示例代码,具有一定的参考价值,... 目录语法示例:使用pandas.concat合并数据默认的concat:参数axis=0,join=

C#代码实现解析WTGPS和BD数据

《C#代码实现解析WTGPS和BD数据》在现代的导航与定位应用中,准确解析GPS和北斗(BD)等卫星定位数据至关重要,本文将使用C#语言实现解析WTGPS和BD数据,需要的可以了解下... 目录一、代码结构概览1. 核心解析方法2. 位置信息解析3. 经纬度转换方法4. 日期和时间戳解析5. 辅助方法二、L

Python使用Code2flow将代码转化为流程图的操作教程

《Python使用Code2flow将代码转化为流程图的操作教程》Code2flow是一款开源工具,能够将代码自动转换为流程图,该工具对于代码审查、调试和理解大型代码库非常有用,在这篇博客中,我们将深... 目录引言1nVflRA、为什么选择 Code2flow?2、安装 Code2flow3、基本功能演示

IIS 7.0 及更高版本中的 FTP 状态代码

《IIS7.0及更高版本中的FTP状态代码》本文介绍IIS7.0中的FTP状态代码,方便大家在使用iis中发现ftp的问题... 简介尝试使用 FTP 访问运行 Internet Information Services (IIS) 7.0 或更高版本的服务器上的内容时,IIS 将返回指示响应状态的数字代