更新视图时为什么我的数组为空? (迅速)

时间:2018-06-04 17:58:37

标签: swift

虽然调试我可以看到控制器中的fixtureList返回6个值。但是,当代码跳转到fixtureView.update(...)中的View时,fixtureList值为0.

我确定它与在控制器和视图中创建相同变量有关,但无法弄明白!

解决此问题的最佳方法是什么?基本上我希望View接收6个值,以便可以填充用户界面。

控制器

var fixtureList = [Fixture]()

func updateScores() {
    liveScoreApi.fetchFixtures() { (
        isOK, fixture) in
        if isOK == true {
                for fixture in (fixture?.fixtures)! {
                    self.fixtureList.append(fixture)
                 }
            self.fixtureView.update(/*dump*/(self.fixtureList))
            }
        else {
            NSLog("error fetching!")
        }
    }
}

查看

class FixtureView: NSView {

@IBOutlet weak var homeNameTextField: NSTextField!
@IBOutlet weak var timeTextField: NSTextField!
@IBOutlet weak var awayNameTextField: NSTextField!

let fixtureList = [Fixture]()

func update(_ fixture: [Fixture]) {
    // do UI updates on the main thread
    DispatchQueue.main.async {
        for fixture in self.fixtureList {
                self.homeNameTextField.stringValue = fixture.homeName
                self.timeTextField.stringValue = fixture.time
                self.awayNameTextField.stringValue = fixture.awayName
                print("added \(fixture.homeName)")
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您的更新方法应如下所示:

//let fixtureList = [Fixture]() // you don't need this

func update(_ fixtureList: [Fixture]) {
    // do UI updates on the main thread
    DispatchQueue.main.async {
        // (though you probably don't want this ultimately)
        for fixture in fixtureList {
            self.homeNameTextField.stringValue = fixture.homeName
            self.timeTextField.stringValue = fixture.time
            self.awayNameTextField.stringValue = fixture.awayName
            print("added \(fixture.homeName)") 
        }
    }
}

问题是你在类级别新建了一个Fixture对象数组。然后,在更新方法中,您尝试迭代新数组而不是传入的数组。

  • 只需在课程级别删除不必要的数组。
  • 将参数名称更改为fixtureList
  • self.你的for循环中删除fixtureList