我刚刚开始使用应该通过Arduino UNO运行DIY数控机器的应用程序。我找到了一些用Objective-C编写的串行通信资源,所以我想我会尝试让它工作。我正在尝试实现一个功能,它将搜索计算机上的可用串行端口,并在下拉菜单中显示它们。
Xcode并没有抱怨任何Objective-C组件,所以我现在假设这不是问题。但是,Xcode给出了错误:“使用未解析的标识符'refreshSerialList'”。这是Apple建议在Swift中调用Objective-C方法的方式:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html
Serial.h
#import <Cocoa/Cocoa.h>
// import IOKit headers
#include <IOKit/IOKitLib.h>
#include <IOKit/serial/IOSerialKeys.h>
#include <IOKit/IOBSD.h>
#include <IOKit/serial/ioss.h>
#include <sys/ioctl.h>
@interface Serial : NSObject {
IBOutlet NSPopUpButton *serialListPullDown;
}
- (void) refreshSerialList: (NSString *) selectedText;
@end
Serial.m
#import "Serial.h"
@implementation Serial
- (void) refreshSerialList: (NSString *) selectedText {
io_object_t serialPort;
io_iterator_t serialPortIterator;
// remove everything from the pull down list
[serialListPullDown removeAllItems];
// ask for all the serial ports
IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching(kIOSerialBSDServiceValue), &serialPortIterator);
// loop through all the serial ports and add them to the array
while (serialPort == IOIteratorNext(serialPortIterator)) {
[serialListPullDown addItemWithTitle:
(__bridge NSString*)IORegistryEntryCreateCFProperty(serialPort, CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0)];
IOObjectRelease(serialPort);
}
// add the selected text to the top
[serialListPullDown insertItemWithTitle:selectedText atIndex:0];
[serialListPullDown selectItemAtIndex:0];
IOObjectRelease(serialPortIterator);
}
@end
桥接Header.h
#import "Serial.h"
AppDelegate.Swift
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet var window: NSWindow!
@IBOutlet var CommandInput : NSView!
@IBOutlet var serialListPullDown : NSPopUpButton!
func applicationDidFinishLaunching(aNotification: NSNotification?) {
// Insert code here to initialize your application
let refresh = refreshSerialList()
}
func applicationWillTerminate(aNotification: NSNotification?) {
// Insert code here to tear down your application
}
@IBAction func CommandSend(sender : AnyObject) {
}
}
答案 0 :(得分:1)
refreshSerialList
接受一个参数,一个字符串。首先,您必须创建一个Serial:
var serial = Serial()
然后在实例上调用方法:
serial.refreshSerialList("some string")