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

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实现全能手机虚拟键盘的示例代码》在数字化办公时代,你是否遇到过这样的场景:会议室投影电脑突然键盘失灵、躺在沙发上想远程控制书房电脑、或者需要给长辈远程协助操作?今天我要分享的Pyth... 目录一、项目概述:不止于键盘的远程控制方案1.1 创新价值1.2 技术栈全景二、需求实现步骤一、需求

Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码

《Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码》:本文主要介绍Java中日期时间转换的多种方法,包括将Date转换为LocalD... 目录一、Date转LocalDateTime二、Date转LocalDate三、LocalDateTim

jupyter代码块没有运行图标的解决方案

《jupyter代码块没有运行图标的解决方案》:本文主要介绍jupyter代码块没有运行图标的解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录jupyter代码块没有运行图标的解决1.找到Jupyter notebook的系统配置文件2.这时候一般会搜索到

Java Optional避免空指针异常的实现

《JavaOptional避免空指针异常的实现》空指针异常一直是困扰开发者的常见问题之一,本文主要介绍了JavaOptional避免空指针异常的实现,帮助开发者编写更健壮、可读性更高的代码,减少因... 目录一、Optional 概述二、Optional 的创建三、Optional 的常用方法四、Optio

Python通过模块化开发优化代码的技巧分享

《Python通过模块化开发优化代码的技巧分享》模块化开发就是把代码拆成一个个“零件”,该封装封装,该拆分拆分,下面小编就来和大家简单聊聊python如何用模块化开发进行代码优化吧... 目录什么是模块化开发如何拆分代码改进版:拆分成模块让模块更强大:使用 __init__.py你一定会遇到的问题模www.

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

使用C#代码在PDF文档中添加、删除和替换图片

《使用C#代码在PDF文档中添加、删除和替换图片》在当今数字化文档处理场景中,动态操作PDF文档中的图像已成为企业级应用开发的核心需求之一,本文将介绍如何在.NET平台使用C#代码在PDF文档中添加、... 目录引言用C#添加图片到PDF文档用C#删除PDF文档中的图片用C#替换PDF文档中的图片引言在当

C#使用SQLite进行大数据量高效处理的代码示例

《C#使用SQLite进行大数据量高效处理的代码示例》在软件开发中,高效处理大数据量是一个常见且具有挑战性的任务,SQLite因其零配置、嵌入式、跨平台的特性,成为许多开发者的首选数据库,本文将深入探... 目录前言准备工作数据实体核心技术批量插入:从乌龟到猎豹的蜕变分页查询:加载百万数据异步处理:拒绝界面

用js控制视频播放进度基本示例代码

《用js控制视频播放进度基本示例代码》写前端的时候,很多的时候是需要支持要网页视频播放的功能,下面这篇文章主要给大家介绍了关于用js控制视频播放进度的相关资料,文中通过代码介绍的非常详细,需要的朋友可... 目录前言html部分:JavaScript部分:注意:总结前言在javascript中控制视频播放

Spring Boot 3.4.3 基于 Spring WebFlux 实现 SSE 功能(代码示例)

《SpringBoot3.4.3基于SpringWebFlux实现SSE功能(代码示例)》SpringBoot3.4.3结合SpringWebFlux实现SSE功能,为实时数据推送提供... 目录1. SSE 简介1.1 什么是 SSE?1.2 SSE 的优点1.3 适用场景2. Spring WebFlu