闽公网安备 35020302035485号
objc_getAssociatedObject 用于返回与指定对象和 key 关联的 value。
enum AssociatedKey {
staticvar key: Int = 0
}
func onButtonTapped() {
// 创建 Alert和负载
let alert = UIAlertController(title: "Title", message: "Example message", preferredStyle: .alert)
let payload = "Example message"
// 使用 objc_setAssociatedObject 函数将负载与 Alert 关联
objc_setAssociatedObject(self, &AssociatedKey.key, payload, .OBJC_ASSOCIATION_RETAIN)
// 为 Alert 添加一个 OK 按钮
let okAction = UIAlertAction(title: "OK", style: .default) { [weakself] _in
self?.handleAlertDismissed()
}
alert.addAction(okAction)
// 堆代码 duidaima.com
// 显示 Alert
present(alert, animated: true, completion: nil)
}
代码解析func handleAlertDismissed() {
// 使用 objc_getAssociatedObject 检索关联负载
if let payload = objc_getAssociatedObject(self, &AssociatedKey.key) {
// 打印负载
print("Payload is: \(payload)") // 输出 "Payload is: Example message"
}
}
释放关键对象objc_setAssociatedObject(self, &AssociatedKey.key, nil, .OBJC_ASSOCIATION_RETAIN)完整代码示例
class ViewController: UIViewController {
// MARK: - Enums
// 用于关联的静态变量键
enum AssociatedKey {
staticvar key: Int = 0
}
// MARK: - Properties
privatevar button: UIButton = {
let button = UIButton()
button.setTitle("Tap me", for: .normal)
button.backgroundColor = .blue
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
// MARK: - View Lifecycles
overridefunc viewDidLoad() {
super.viewDidLoad()
setupUI()
button.addTarget(self, action: #selector(onButtonTapped), for: .touchUpInside)
}
}
// MARK: - Private Methods
extension ViewController {
func setupUI() {
view.addSubview(button)
button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
@objcfunc onButtonTapped() {
// 创建 Alert 和负载
let alert = UIAlertController(title: "Title", message: "Example message", preferredStyle: .alert)
let payload = "Example message"
// 使用 objc_setAssociatedObject 函数将负载与 Alert 关联
objc_setAssociatedObject(self, &AssociatedKey.key, payload, .OBJC_ASSOCIATION_RETAIN)
// 为 Alert 添加一个 OK 按钮
let okAction = UIAlertAction(title: "OK", style: .default) { [weakself] _in
self?.handleAlertDismissed()
}
alert.addAction(okAction)
// 堆代码 duidaima.com
// 显示 Alert
present(alert, animated: true, completion: nil)
}
func handleAlertDismissed() {
// 使用 objc_getAssociatedObject 检索关联负载
iflet payload = objc_getAssociatedObject(self, &AssociatedKey.key) {
// 打印负载
print("Payload is: \(payload)") // 输出 "Payload is: Example message"
}
}
}
总结