我来自java编程背景。我试图从classB设置classA的实例变量,这样就可以使用其他变量进行计算,这些变量进入Realm并用于使用RXSwift与蓝牙进行通信,所以我试图将对象类型Measurement转换为TestRes。
public class classA {
var mTestResult:TestRes?
func setTestResult(measurement:Measurement){
self.mTestResult?.id = measurement.measurementId
print("Test Id: \(self.mTestResult?.id)")
print("Measured Id: \(measurement.measurementId)")
self.mTestResult?.oilType = measurement.oilType
print("Test Oil Type: \(self.mTestResult?.oilType)")
print("Measured Oil Type: \(measurement.oilType)")
}
}
ClassB的功能如下:
public class ClassB{
private func send304and306(measurement: Measurement, connectedPeripheral: Peripheral) -> Observable<Measurement> {
let response2 = MeasurementData(response: response)
//added
dump(measurement)
let results = HW2_1_Calculate()
results.setTestResult(measurement: measurement)
results.run()//CRASH HERE because my measurements are not being set
realm.add(results.mTestResult, update: true)
print("about to dump results")
dump(results)
try realm.commitWrite()
}
}
我从调试器得到的输出是
测试ID:无
测量标识:13fvasl-f4vr-4fsb-4kgv-4kvlvnfsv
试油类型:零
测量油类型:
我的TestRes类型的实例变量进入领域数据库,看起来像这样。
class TestRes: Object {
@objc dynamic var id:String = ""
@objc dynamic var oilType:String = ""
}
class Measurement: Object {
@objc dynamic var measurementId = UUID().uuidString
@objc dynamic var oilType: String = ""
}
实际上,TestRes比Measurement更复杂。无论如何为什么ClassA实例var没有设置为我告诉它等于的值?
答案 0 :(得分:0)
当我发布它之后,我想出了如何解决这个问题。
无论如何我没有使用init()来构造对象! 为了解决我的问题,我把它放在ClassA
中init(measurement:Measurement){
self.mTestResult = setTestResult(measurement: measurement)
print("Test Id: \(self.mTestResult?.id)")
}
然后在ClassB中我用下面的构造函数创建了对象。
let results = HW2_1_Calculate(measurement:measurement)