iOS26适配指南之通知

介绍

  • UIKit 带来了强类型通知,为通知系统带来了期待已久的类型与并发安全性。
  • 不再使用基于字符串的标识符以及通过userInfo字典传递数据,该种方式存在线程安全、拼写错误、类型转换等问题。
  • 通过全新的并发安全通知协议NotificationCenter.MainActorMessage(主线程消息)与NotificationCenter.AsyncMessage(异步消息)可以做到编译时检测,从而提前发现潜在的问题。
  • 与老版本的通知系统完全兼容。

使用

  • 代码。
swift 复制代码
import UIKit

public class NotificationSubject {
    static let shared = NotificationSubject()
}

// MARK: - 消息类型
public struct CustomMainActorMessage: NotificationCenter.MainActorMessage {
    // 发送者
    public typealias Subject = NotificationSubject
    public static var name: Notification.Name {
        .init("CustomMainActorMessage")
    }

    // 数据
    let info: String
}

class ViewController: UIViewController {
    lazy var label: UILabel = {
        let label = UILabel()
        label.frame = CGRect(x: 0, y: 0, width: 300, height: 60)
        label.textAlignment = .center
        label.text = "暂无通知消息"
        label.center = view.center
        return label
    }()

    var mainActorMessageToken: NotificationCenter.ObservationToken!

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(label)
        // 监听通知
        mainActorMessageToken = NotificationCenter.default.addObserver(of: NotificationSubject.shared, for: CustomMainActorMessage.self) { message in
            self.label.text = "\(message.info)"
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        // 发送通知
        NotificationCenter.default.post(CustomMainActorMessage(info: "you have a new message"), subject: NotificationSubject.shared)
    }

    deinit {
        NotificationCenter.default.removeObserver(mainActorMessageToken)
    }
}
  • 效果。
相关推荐
RyanGo1 小时前
iOS断点下载
ios·swift
蒙小萌19932 小时前
找工作-iOS开发-3年经验-AI协作开发
ios
丶皮蛋菌4 小时前
关于OC与Swift内存管理的解惑
ios
杂雾无尘5 小时前
掌握生死时速:苹果应用加急审核全攻略!
ios·swift·apple
HarderCoder5 小时前
Swift 6.2 中的 `@concurrent`
ios·swift
Digitally7 小时前
如何将文件从 iPhone 传输到 Android(新指南)
android·ios·iphone
木叶丸8 小时前
跨平台方案该如何选择?
android·前端·ios
我唔知啊9 小时前
OC底层原理二:OC对象的分类(实例对象、类对象、元类对象)
ios·objective-c
泓博10 小时前
KMP(Kotlin Multiplatform)改造(Android/iOS)老项目
android·ios·kotlin