加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

将CFString转换为NSString – Swift

发布时间:2020-12-14 05:37:05 所属栏目:百科 来源:网络整理
导读:我正在尝试编写一个程序,将扫描可用的串行端口并将其显示在弹出菜单中.为什么不能直接从IORegistryEntryCreateCFProperty()函数中获取CFString,并在下一行通过字符串插值将其添加到菜单中?由于某种原因,我的变量声明遇到错误: “NSString is not a subtype
我正在尝试编写一个程序,将扫描可用的串行端口并将其显示在弹出菜单中.为什么不能直接从IORegistryEntryCreateCFProperty()函数中获取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.String和NSString是免费的桥接.

NSString和CFString可以彼此转换,但是您不能直接从Swift String转换为CFString,反之亦然.

按照以下步骤从Core Foundation String转换为Swift字符串:

var cfStr:CFString = "Soon,I'll be a Swift String"
var nsTypeString = cfStr as NSString
var swiftString:String = nsTypeString

CFTypeRef示例:

var cfStr:CFTypeRef = "Soon,I'll be a Swift String"
var nsTypeString = cfStr as NSString
var swiftString:String = nsTypeString

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读