0

基本上,它可以很好地传递数组。只是在尝试将枚举数组用作 tablerows 时,它说 nil found。

电话

import UIKit
import WatchConnectivity

class ViewController: UIViewController, WCSessionDelegate {

    @IBOutlet weak var sendButton: UIButton!

    var watchSession: WCSession?
    var arrayCustom = ["thing1", "thing2"]

    override func viewDidLoad() {
        super.viewDidLoad()

        if(WCSession.isSupported()) {
            watchSession = WCSession.defaultSession()
            watchSession?.delegate = self
            watchSession?.activateSession()
        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


    @IBAction func sendArray(sender: AnyObject) {
        sendToWatch()

    }


    private func sendToWatch() {
        do {
            let applicationDict = ["Array1": arrayCustom]
            try WCSession.defaultSession().updateApplicationContext(applicationDict)
        }

        catch {
            print(error)
        }
    }
}

手表

private func loadThCust() {

        if (WCSession.isSupported()) {
            watchSession = WCSession.defaultSession()
            watchSession.delegate = self;
            watchSession.activateSession()]
        }

func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {

        dispatch_async(dispatch_get_main_queue()) { () -> Void in

            if let retrievedArray1 = applicationContext["Array1"] as? [String] {
                self.custArray = retrievedArray1
                print(self.custArray)
            }
            for (index, thName) in self.custArray.enumerate() {
                let row2 = self.choiceTable.rowControllerAtIndex(index) as! ChoiceTableRowController
                row2.choiceLabel.setText(thName)
                }
            }
        }

我的问题是每当我尝试加载 TableView 时都会收到此控制台输出 + 错误:

["thing1", "thing2"]
2016-02-24 03:21:25.912 WristaRoo WatchKit Extension[9401:243561] Error - attempt to ask for row 0. Valid range is 0..0
fatal error: unexpectedly found nil while unwrapping an Optional value

有谁知道为什么展开的值仍然为零?我希望一旦我设置它并且可以看到 [String] 数组中有值,它可以枚举它,但似乎它们只是不可见的。

4

1 回答 1

2

您以“基本上,它很好地传递了数组”的声明开始了这个问题,所以这不是 Watch Connectivity 问题。

choiceTable在遍历数组之前,您只是没有指定行数。

choiceTable.setNumberOfRows(custArray.count, withRowType: "ChoiceTableRowController")

从控制台输出确定问题:

  • 错误 - 尝试请求第 0 行。有效范围是 0..0

    rowControllerAtIndex:当它的索引超出范围时返回(一个可选的)nil。

    行控制器对象,如果还没有行控制器或索引超出范围,则为 nil。

    您试图访问不存在的行,导致边界警告。

  • 致命错误:在展开可选值时意外发现 nil

    row2.choiceLabel.setText(thName)
    

    row2是零。

您应该能够在调试器中轻松追踪此类错误。如果您检查row2并看到它是 nil,您会意识到问题不在于数组本身,而在于该表没有行。

于 2016-02-24T10:59:06.357 回答