【问题标题】:Swift UnsafeMutableRawPointer returns class instead of instanceSwift UnsafeMutableRawPointer 返回类而不是实例
【发布时间】:2019-12-29 17:05:13
【问题描述】:

我希望这段代码返回一个 NSString 和当前选择的输入源的 ID。相反,它似乎返回了 NSString 类之一。

import Foundation
import Carbon

let current = TISCopyCurrentKeyboardInputSource().takeUnretainedValue()

let id = TISGetInputSourceProperty(current, kTISPropertyInputSourceID).load(as: NSString.self)
id.length

当我在我的 macOS 应用程序中运行它时,我在日志中收到以下错误消息:+[__NSCFConstantString _fastCStringContents:]: unrecognized selector sent to class 0x7fff92cf79e8。如何解决此问题以便获得正确的返回值?

【问题讨论】:

    标签: swift pointers macos-carbon


    【解决方案1】:

    TISGetInputSourceProperty() 返回一个(非托管)原始指针,该指针必须转换CFStringRef,而不是取消引用 load()。然后可以将CFString 桥接到 Swift String

    let current = TISCopyCurrentKeyboardInputSource().takeRetainedValue()
    if let ptr = TISGetInputSourceProperty(current, kTISPropertyInputSourceID) {
        let id = Unmanaged<CFString>.fromOpaque(ptr).takeUnretainedValue() as String
        print(id) // com.apple.keylayout.German
    }
    

    另请注意,takeRetainedValue() 必须用于 TISCopyCurrentKeyboardInputSource() 的返回值,因为该函数返回 (+1) 保留引用,否则会出现内存泄漏。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多