2015-06-17 26 views
2

我在Swift中編寫了一個iOS應用程序,並且存在一些關於結構和塊的問題。當用戶編輯他的教育信息並點擊保存按鈕時,我向服務器發送請求並更新成功處理程序中的本地數據。在這裏,我寫的類EditControllereditItem()功能和類UserModel結構的editEducation()Swift結構在塊中修改後沒有更新

class EditController: UITableViewController { 

    //... 

    func editItem<T>(item: T, completion:() -> Void) { 
     switch selectedType { 
      case .Education: 
       let educationItem = item as! EducationModel 
       // self.user is a object of type "UserModel" 
       user!.editEducation(index: selectedRow, educationItem: educationItem) { 
        // breakpoint 2 here 
        completion() 
        self.tableView.reloadData() 
       } 
      default: 
       return 
     } 
    } 

    //... 

} 

struct UserModel { 

    //... 

    var education = [EducationModel]() 
    //EducationModel is also a structure 

    //... 

    mutating func editEducation(#index: Int, educationItem: EducationModel, completion:() -> Void) { 
     let manager = HTTPClient.sharedManager 
     manager.POST("/user/education/update", 
      parameters: [ 
       // params 
      ], 
      success: { (task, responseObject) in 
       if responseObject["status"] as! Int == 0 { 
        self.education[index] = educationItem 
        // breakpoint 1 here 
        completion() 
       } else { 
        println(responseObject) 
       } 
      }, 
      failure: { (task, error) in 
       println(error) 
      } 
     ) 
    } 

    //... 

} 

的問題是,儘管self.education成功更新在程序到達斷點1(如上評論),self.user.education仍包含斷點2.舊數據如果我提出

self.education[index] = educationItem 

POST請求外,數據的更新,在斷點2.我試圖通過斷點2加入調度延遲預期,但它仍然不會更新。我還打印了相關變量的內存地址,但它沒有提供有用的信息。我現在通過將controller參數添加到editEducation,通過selfEditController並強制更新控制器的user屬性來處理此問題。我認爲這不是一個合適的解決方案。那麼有沒有更好的方法來做到這一點?

更新1

我試圖圖靈的usermodel成類,它解決了這個問題,但我不想這樣做,因爲:第一應用程序的其它部分的一些行爲可能如果我去怪做一個班級,其次我必須將其他幾十個模型轉換成班級,以確保一致性。

回答

5

你在這裏看到的是值類型(結構)和引用類型(類)之間的差異。你應該閱讀蘋果公司網站上關於差異的博客文章:https://developer.apple.com/swift/blog/?id=10

基本上,一旦你將一個結構體傳遞給一個塊,它將被複制而不是被引用,所以你正在研究一個全新的副本。通過課程,您可以獲得對原始副本的參考。

+0

我試着在editEducation()的外部和內部的成功塊中打印self的內存,結果證明它們是相同的。這是否意味着在進入該塊時不會複製該值? – qinbingchen

+1

他們在寫*時被複制*。即使被複制直到被修改,所有引用類型也將是相同的實例。我猜你在修改它之前檢查了地址*? –