我正在尝试更新一个类变量(预测),然后将该变量用作segue(AnalyzeSegue)的数据。但是,即使我在函数 (detectScene) 中更新了类变量,类变量也是nil
为 segue 做准备期间的一个值,导致我的应用程序崩溃。
大部分代码是通过本教程(只是为我的模型定制):
https://www.raywenderlich.com/577-core-ml-and-vision-machine-learning-in-ios-11-tutorial
class PreviewViewController: UIViewController {
var prediction: String?
@IBOutlet weak var Photo: UIImageView!
//This button is what starts the segue into the next screen(
@IBAction func analyze(_ sender: Any) {}
override func prepare(for segue: UIStoryboardSegue, sender: Any?){
if segue.identifier == "saveSegue"{
"save photo"}
else if segue.identifier == "AnalyzeSegue" #Analyze button
{
let AnalyzeVC = segue.destination as! AnalyzeViewController
let ciImage = CIImage(image:Photo.image!)
self.detectScene(image: ciImage!)
print(self.prediction!) #nil value
if let hasPrediction = self.prediction {
AnalyzeVC.predictionLabel.text = hasPrediction
AnalyzeVC.imagePreview.image = Photo.image}
}
检测功能:
extension PreviewViewController{
func detectScene(image: CIImage) {
var localPrediction: String?
// Load the ML model through its generated class
guard let model = try? VNCoreMLModel(for: test2().model)
else {
fatalError("can't load Places ML model")
}
let request = VNCoreMLRequest(model: model) { [weak self] request, error in
guard let results = request.results as? [VNCoreMLFeatureValueObservation]
else {
fatalError("unexpected result type from VNCoreMLRequest")
}
let topResult = results.first?.featureValue.multiArrayValue
DispatchQueue.main.async { () in
var max_value : Float32 = 0
for i in 0..<topResult!.count{
if max_value < topResult![i].floatValue{
max_value = topResult![i].floatValue
localPrediction = String(i)
}
} //#end of loop
self?.prediction = localPrediction #update self?.prediction
print(self?.prediction, "Inside Function") #seems to have value
} //#end of dispatch Queue
} //#end of closure
let handler = VNImageRequestHandler(ciImage: image)
DispatchQueue.global(qos: .userInteractive).async {
do {
try handler.perform([request])
} catch {print(error)}
}
} //end of function
} //end of extension
因此,该detectScene
函数应该更新类变量prediction
,并且该信息用于准备 seugue 函数。该函数似乎是更新值,因为我在函数中有一个打印语句正在打印出一个可选值:
print(self?.prediction, "Inside Function")
谢谢您的帮助。