更新扩展委托中的数组

Update array in Extension Delegate

我正在使用 ExtensionDelegate,因此我可以从我的 InterfaceController(最终 ComplicationController)访问 evnts 变量。

当我从 WCSession, didReceiveUserInfo 获取数据时,我 需要在 ExtensionDelegate 中刷新 evnts,但我不太清楚如何,有什么想法吗?

原因是:evnts 是空的,因为它在 WCSession, didReceiveUserInfo 运行以实际获取数据之前被调用。

(如有任何问题请告诉我,并将 post 根据需要提供任何额外代码!)

ExtensionDelegate:

class ExtensionDelegate: NSObject, WKExtensionDelegate {
    var evnts = [Evnt]()
}

InterfaceController:

func session(session: WCSession, didReceiveUserInfo userInfo: [String : AnyObject]) {

    if let tColorValue = userInfo["TeamColor"] as? String, let matchValue = userInfo["Matchup"] as? String {

        let myDelegate = WKExtension.sharedExtension().delegate as! ExtensionDelegate
        var extEvnts = myDelegate.evnts

        receivedData.append(["TeamColor" : tColorValue , "Matchup" : matchValue])
        extEvnts.append(Evnt(dataDictionary: ["TeamColor" : tColorValue , "Matchup" : matchValue]))

        doTable()

    } else {
        print("tColorValue and matchValue are not same as dictionary value")
    }

}


func doTable() {

    let myDelegate = WKExtension.sharedExtension().delegate as! ExtensionDelegate
    let extEvnts = myDelegate.evnts

    self.rowTable.setNumberOfRows(extEvnts.count, withRowType: "rows")

    for (index, evt) in extEvnts.enumerate() {

        if let row = rowTable.rowControllerAtIndex(index) as? TableRowController {

            row.mLabel.setText(evt.eventMatch)
            row.cGroup.setBackgroundColor(colorWithHexString(evt.eventTColor)) 
        } else {
            print("nope")
        }
    }    
}

您可以将 ExtensionDelegate 中的 evnts 设为静态变量

class ExtensionDelegate: NSObject, WKExtensionDelegate {
    static var evnts = [Evnt]()
}

然后您还需要进行更改:

func session(session: WCSession, didReceiveUserInfo userInfo: [String : AnyObject]) {

    if let tColorValue = userInfo["TeamColor"] as? String, let matchValue = userInfo["Matchup"] as? String {

        receivedData.append(["TeamColor" : tColorValue , "Matchup" : matchValue])
        ExtensionDelegate.evnts.append(Evnt(dataDictionary: ["TeamColor" : tColorValue , "Matchup" : matchValue]))

        doTable()

    } else {
        print("tColorValue and matchValue are not same as dictionary value")
    }

}

func doTable() {

    let extEvnts = ExtensionDelegate.evnts

    self.rowTable.setNumberOfRows(extEvnts.count, withRowType: "rows")

    for (index, evt) in extEvnts.enumerate() {

        if let row = rowTable.rowControllerAtIndex(index) as? TableRowController {

            row.mLabel.setText(evt.eventMatch)
            row.cGroup.setBackgroundColor(colorWithHexString(evt.eventTColor)) 
        } else {
            print("nope")
        }
    }    
}