首先:我要做的是找到连接到mac的设备,方法是调用
ls /dev/tty.usbmodem*
终端中的确实如此 但是通过使用IOKit
其次,这是我的代码:
@IBAction func testPressed(sender: AnyObject) {
var portIterator: io_iterator_t = 0
let kernResult = findSerialDevices(kIOSerialBSDModemType, serialPortIterator: &portIterator)
if kernResult == KERN_SUCCESS {
printSerialPaths(portIterator)
}
}
func findSerialDevices(deviceType: String, inout serialPortIterator: io_iterator_t ) -> kern_return_t {
var result: kern_return_t = KERN_FAILURE
var classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue).takeUnretainedValue()
var classesToMatchDict = (classesToMatch as NSDictionary) as Dictionary<String, AnyObject>
classesToMatchDict[kIOSerialBSDTypeKey] = deviceType
let classesToMatchCFDictRef = (classesToMatchDict as NSDictionary) as CFDictionaryRef
result = IOServiceGetMatchingServices(kIOMasterPortDefault, classesToMatchCFDictRef, &serialPortIterator);
return result
}
func printSerialPaths(portIterator: io_iterator_t) {
var serialService: io_object_t
do {
serialService = IOIteratorNext(portIterator)
if (serialService != 0) {
let key: CFString! = "IOCalloutDevice"
let bsdPathAsCFtring: AnyObject? = IORegistryEntryCreateCFProperty(serialService, key, kCFAllocatorDefault, 0).takeUnretainedValue()
var bsdPath = bsdPathAsCFtring as String?
if let path = bsdPath {
println(path)
}
}
} while serialService != 0;
}
当我在命令行工具(新项目&gt; os x&gt;命令行工具)中运行它时,它运行良好。 (我基本上只编写相同的代码,而且#testffressed&#39;函数中的四行不在IBAction中)
控制台输出:
/dev/cu.Bluetooth-Modem
/dev/cu.usbmodem1411
当我从cocoa mac应用程序运行它时,它在正确执行代码后崩溃:
/dev/cu.Bluetooth-Modem
/dev/cu.usbmodem1411
serialTests(40925,0x7fff77354300) malloc: *** error for object 0x61000003243c: Invalid pointer dequeued from free list
*** set a breakpoint in malloc_error_break to debug
(lldb)
我研究了这个,搜索了错误,阅读了IOKit基础知识应用程序开发人员指南,在一个单独的项目中重新编写代码以确保其他内容没有错项目我没有注意到。 我仍然无法修复错误