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)
    }
}
  • 效果。
相关推荐
白玉cfc6 小时前
【iOS】网易云仿写
ui·ios·objective-c
归辞...8 小时前
「iOS」——内存五大分区
macos·ios·cocoa
HX4369 小时前
MP - List (not just list)
android·ios·全栈
忆江南13 小时前
NSProxy是啥,用来干嘛的
ios
忆江南13 小时前
dyld
ios
归辞...1 天前
「iOS」——GCD其他方法详解
macos·ios·cocoa
游戏开发爱好者81 天前
没有 Mac,如何上架 iOS App?多项目复用与流程标准化实战分享
android·ios·小程序·https·uni-app·iphone·webview
Digitally2 天前
如何将 iPhone 备份到 Mac/MacBook
macos·ios·iphone
songgeb2 天前
Concurrency in Swift学习笔记-初识
ios·swift
mobsmobs2 天前
Flutter开发环境搭建与工具链
android·flutter·ios·android studio·xcode