2017-10-05 79 views
1

我有一個跟蹤我的遊戲得分的單身人士課程。如何防止Swift 4重疊或獨佔訪問錯誤?

final class PublicData { 
    static let sharedInstance: PublicData? = PublicData() 

    struct Scores { 
     var points = [0, 0] 
     subscript(index: Int) -> Int { 
      get {return points[index]} 
      set(newValue) { 
       points[index] += newValue 
       print("score\(index): \(points[index])") 
       NotificationCenter.default.post(name: Notification.Name(rawValue: "updateScore\(index)"), object: nil) 
      } 
     } 
     mutating func reset() { 
      points = [0, 0] 
      NotificationCenter.default.post(name: Notification.Name(rawValue: "updateScore0"), object: nil) 
      NotificationCenter.default.post(name: Notification.Name(rawValue: "updateScore1"), object: nil) 
     } 
    } 


    var scores = Scores() 
} 

然後在我的RootViewController中,我更新視圖以匹配當前分數。

let data = PublicData.sharedInstance 

@objc func updateScore0(_ payload: Notification) { 
    let score = data!.scores[0] // line 678 
    score0.text = "\(score)" 
    // I use matchsticks to show the score 
    setMatchScore(score, matchesView: matchesStack0) 
} 

@objc func updateScore1(_ payload: Notification) { 
    let score = data!.scores[1] 
    score1.text = "\(score)" 
    setMatchScore(score, matchesView: matchesStack1) 
} 

現在斯威夫特4我得到的線這個錯誤678

「主題1:同時訪問0x608000186ad8,但修飾 需要獨佔訪問

我已經嘗試使用let temp = points和使用溫度代替,但它沒有工作。 任何人都可以幫助解決一個解決方案?


這個問題已被批評爲已被回答。然而,「答案」僅僅是一段視頻的鏈接,雖然解釋了錯誤的概念和原因,但並沒有解釋我爲什麼遇到錯誤。

大部分編碼原理都被記錄在案。堆棧溢出幫助那些還沒有圍繞在他們頭上的人。

指示文件/視頻方向的提問者是徒勞的。有時候,親自關注您與您的問題的人不僅會更快地解決問題,而且會爲將來類似的難以理解的概念開啓燈光。


+0

的可能的複製[同時訪問0x1c0a7f0f8,但修改需要上的Xcode 9測試4獨佔訪問錯誤](https://stackoverflow.com/questions/45415901/simultaneous-access-to-0x1c0a7f0f8-but-modification-requires-exclusive-access) – the4kman

+0

我看了一下。它沒有幫助我。 –

回答

0

我解決了我的困境。

我只是將通知中的有效載荷數據從結構傳遞到RootViewController,而不是從RootViewController讀取結構屬性。

RootViewController的代碼

@objc func updateScore0(_ payload: Notification) { 
    if let score = payload.userInfo?["score"] as? Int { 
     score0.text = "\(score)" 
     setMatchScore(score, matchesView: matchesStack0) 
    } 
} 

STRUCT代碼

struct Scores { 
    var points = [0, 0] 
    subscript(index: Int) -> Int { 
     get {return points[index]} 
     set(newValue) { 
      points[index] += newValue 
      let payload: [String: Int] = ["score": points[index]] 
      print("score\(index): \(points[index])") 
      NotificationCenter.default.post(name: Notification.Name(rawValue: "updateScore\(index)"), object: nil, userInfo: payload) 
     } 
    } 
    mutating func reset() { 
     points = [0, 0] 
     let payload0: [String: Int] = ["score": points[0]] 
     let payload1: [String: Int] = ["score": points[1]] 
     NotificationCenter.default.post(name: Notification.Name(rawValue: "updateScore0"), object: nil, userInfo: payload0) 
     NotificationCenter.default.post(name: Notification.Name(rawValue: "updateScore1"), object: nil, userInfo: payload1) 
    } 
}