You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

macOS中如何将NSEvent转换为字符串数组或字符串对象?

如何将NSEvent转换为可序列化的字符串对象/数组(用于JSON转换)?

问题背景

你实现的macOS鼠标点击事件监听代码:

let eventObserver = NSEvent.addGlobalMonitorForEvents(matching: NSEvent.EventTypeMask.leftMouseDown) { (event) -> Void in
    Swift.print("Event is \(event)")
}

点击后输出:

Event is NSEvent: type=LMouseDown loc=(248.664,269.775) time=12673.2 flags=0 win=0x0 winNum=91 ctxt=0x0 evNum=905 click=1 buttonNumber=0 pressure=1 deviceID:0x300000014400000 subtype=NSEventSubtypeTouch

需要将NSEvent实例转换为可处理的字符串对象/数组,最终转为JSON格式。


解决方案

直接提取NSEvent的公开属性封装成字典(便于JSON序列化),或按需转为字符串数组,不建议解析系统打印的description内容(格式无公开规范,易随系统版本变化)。

1. 提取属性为字典(推荐,适配JSON转换)

通过扩展NSEvent,按需提取关键属性生成字典:

import Foundation

extension NSEvent {
    func toDictionary() -> [String: Any] {
        var eventDict: [String: Any] = [:]
        // 事件类型(原始值)
        eventDict["eventType"] = self.type.rawValue
        // 点击坐标
        eventDict["location"] = ["x": self.locationInWindow.x, "y": self.locationInWindow.y]
        // 时间戳
        eventDict["timestamp"] = self.timestamp
        // 点击次数
        eventDict["clickCount"] = self.clickCount
        // 按钮编号
        eventDict["buttonNumber"] = self.buttonNumber
        // 设备ID
        eventDict["deviceID"] = self.deviceID
        // 事件子类型
        eventDict["subtype"] = self.subtype.rawValue
        // 可根据需求添加更多属性,比如flags、windowNumber等
        return eventDict
    }
}

使用示例(转换为JSON):

let eventObserver = NSEvent.addGlobalMonitorForEvents(matching: .leftMouseDown) { event in
    let eventDict = event.toDictionary()
    // 转换为JSON字符串
    if let jsonData = try? JSONSerialization.data(withJSONObject: eventDict, options: .prettyPrinted),
       let jsonString = String(data: jsonData, encoding: .utf8) {
        print("JSON格式事件数据:\n\(jsonString)")
    }
}

2. 转换为字符串数组

基于上述字典,生成键值对格式的字符串数组:

extension NSEvent {
    func toStringArray() -> [String] {
        let eventDict = self.toDictionary()
        return eventDict.map { "\($0.key): \($0.value)" }
    }
}

使用示例:

let eventObserver = NSEvent.addGlobalMonitorForEvents(matching: .leftMouseDown) { event in
    let stringArray = event.toStringArray()
    print("字符串数组:\(stringArray)")
}

内容的提问来源于stack exchange,提问作者Ravindu Tharanga Perera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 09:50:36