我正在尝试按照 MetaWear 指南启动示例应用程序,位于 h ere .我很快遇到的问题是我遇到了意外崩溃。这是我的代码的结构
最后,我的 Podfile 包含以下内容:
platform :osx, '10.12.6'
target 'meta-wear' do
use_frameworks!
pod 'MetaWear', '~> 2.9'
end
当我运行应用程序时,我在第一张图片的第 5 行收到如下线程异常:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
虽然我当然是新的 Swift 开发人员(菜鸟),但我不知道为什么我无法复制他们的指南。
Xcode:9.0 macOS Sierra 版本 10.12.6(这是我要运行此命令行应用程序的地方)
添加无限循环后更新
我更新了 main.swift 类以实现以下内容:
import Foundation
let runLoop = RunLoop.current;
let distantFuture = Date.distantFuture;
print("### we are in the create");
let starter = MetaWearStarter();
print("### we are after the create");
while (runLoop.run(mode: RunLoopMode.defaultRunLoopMode, before: distantFuture)){
print("### listening for a metawear device");
}
我创建了一个名为 MetaWearStarter.swift 的类,如下所示:
import Foundation
import MetaWear
class MetaWearStarter : NSObject {
override init() {
super.init();
print("### we are in the init");
startConnection();
}
func startConnection() {
print("##### connection call was made");
let manager = MBLMetaWearManager.shared();
maanger.startScanForMetaWears() { array in
print("### connection scan was complete")
// Hooray! We found a MetaWear board, so stop scanning for more
MBLMetaWearManager.shared().stopScan()
// Connect to the board we found
if let device = array.first {
device.connectAsync().success() { _ in
print("#### we connected to a device");
}.failure() { error in
print("### unable to connect");
}
}
}
}
}
我在这一行得到了之前的错误:
let manager = MBLMetaWearManager.shared();
而且我的输出永远不会超过那条线:
### we are in the create
### we are in the init
##### connection call was made
最佳答案
让runloop保持运行的无限循环不是一个好习惯。
向您的类添加完成处理程序并在完成时停止运行循环。
在 CLI 中处理运行循环的常用方法是这样的:
import Foundation
import MetaWear
class MetaWearStarter {
let manager = MBLMetaWearManager.shared()
func startConnection(completion: @escaping (String)->()) {
print("##### connection call was made");
manager.startScanForMetaWears() { array in
print("### connection scan was complete")
// Hooray! We found a MetaWear board, so stop scanning for more
manager.stopScan()
// Connect to the board we found
if let device = array.first {
device.connectAsync().success() { _ in
completion("#### we connected to a device")
}.failure() { error in
completion("### unable to connect, error: \(error.localizedDescription)")
}
} else {
completion("#### no device found")
}
}
}
}
let starter = MetaWearStarter()
let runLoop = RunLoop.current
starter.startConnection { (result) in
print(result)
CFRunLoopStop(runLoop.getCFRunLoop())
}
runLoop.run()
exit(EXIT_SUCCESS)
关于swift - 元磨损 : CLI application on MACOSX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46435965/