将 CFString 转换为 NSString - Swift [英] Convert CFString to NSString - Swift

查看:113
本文介绍了将 CFString 转换为 NSString - Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个程序来扫描可用的串行端口并在弹出菜单中显示它们.为什么我不能直接从 IORegistryEntryCreateCFProperty() 函数中获取 CFString 并通过下一行的字符串插值将其添加到菜单中?出于某种原因,我的变量声明遇到了错误:

I'm trying to write a program that will scan for available serial ports and present them in a popup menu. Why can I not take the CFString straight from the IORegistryEntryCreateCFProperty() function and add it to the menu via string interpolation in the next line? For some reason my variable declaration is met with the error:

NSString 不是 CFString 的子类型".

"NSString is not a subtype of CFString".

import Foundation

import Cocoa

import IOKit
import IOKit.serial


@objc class Serial {

    init() {
    }

    @IBOutlet var serialListPullDown : NSPopUpButton!

    func refreshSerialList(defaultprompt: String) {


        let masterPort: mach_port_t = kIOMasterPortDefault
        let classesToMatch: CFDictionary =     IOServiceMatching(kIOSerialBSDServiceValue).takeUnretainedValue()
        var matchingServices: io_iterator_t = 0

        // remove everything from the pull down list
        serialListPullDown?.removeAllItems()

        // ask for all the serial ports
        let kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch, &matchingServices)
        if kernResult == KERN_SUCCESS {
            // success
            while (io_object_t() == IOIteratorNext(matchingServices)) {
                var serialport = IORegistryEntryCreateCFProperty(io_object_t(), kIOCalloutDeviceKey, kCFAllocatorDefault, 0)

                serialListPullDown?.addItemWithTitle("\(serialport)")
            }
        }
        else {
            // error
        }

    }
}

推荐答案

至少从 Swift 2.0 开始(从终端使用 swift --version 验证),您可以使用简单的 as StringCFString 转换为原生 Swift String.

At least as of Swift 2.0 (verify from a terminal with swift --version), you can convert a CFString to a native Swift String with a simple as String.

这就足够了,因为 Swift 的 String 类型可以在任何需要 NSString 的地方使用.

This is sufficient, since Swift's String type can be used anywhere NSString is expected.

一个带有 kUTType* 常量的 example(kUTType* 常量由 CoreServices 定义并且是 CFStrings):

An example with a kUTType* constant (kUTType* constants are defined by CoreServices and are CFStrings):

// Get UTF8 plain text from the pasteboard.
import AppKit
let str = NSPasteboard.generalPasteboard().stringForType(kUTTypeUTF8PlainText as String)

一个更详细的例子:

// Import at least the Foundation framework.
// Since Cocoa includes Foundation, `import Cocoa` works too.
// (Note that `import CoreServices`, even though it defines type `CFString`,
// is NOT enough - the conversion will fail.)
import Foundation

// Create a CFString.
// The fact that initializing from a `String` literal here works implies that
// the *reverse* cast - String -> CFString - also works.
var cfStr:CFString = "Cast me."

// Convert it to String.
var swiftStr = cfStr as String

<小时>

测试您正在处理的类型:

cfStr is CFString // true
swiftStr is String // true

获取字符串的类型,请使用.dynamicType;在字符串上下文中,这会报告类型名称,但请注意,您可能会返回一个私有内部类的名称:

To get the string's type, use .dynamicType; in a string context, this reports the type name but note that you may get the name of a private internal class back:

"cfStr is a \(cfStr.dynamicType) instance."
// -> "cfStr is a _NSContiguousString instance." !!

不过,您可以将其视为 CFString,如上面的 is 测试所示.

Still, you can treat this as a CFString, as the is test above shows.

使用 _stdlib_getDemangledTypeName() 获取真实的底层类名:

_stdlib_getDemangledTypeName(cfStr) // -> "ObjectC.CFString"
_stdlib_getDemangledTypeName(kUTTypeUTF8PlainText) // ditto

这篇关于将 CFString 转换为 NSString - Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆