2016-10-24 9 views
0

SQL Serverからデータを取得しようとしていますが、データを格納できません。私はすべての行を取得していますが、データはゼロです。それは、私がデータを持っている私はDBから切断する前に、私はすべてのデータが消えた接続を閉じるときを意味します。SwiftのSQLClient経由でSQL Serverからデータを引き出す

私は浅いコピーを持っていると私は、私はあなたが右の閉鎖後、印刷レシピを実行しているためであると考え

import Foundation 
import SQLClient 

class RecipeViewModel{ 
var recipes = [Recipe]() 

init(){ 
    getRecipeFromDB() 
} 

func getRecipeFromDB(){ 

    let client = SQLClient.sharedInstance() as! SQLClient 

    client.connect("x.x.x.x", username: "xx", password: "xxx", database: "xxx") { 
     success in 
     client.execute("SELECT item FROM TABLE") { 
      results in 

      for table in results as! [[[String:AnyObject]]] { 
       for row in table { 

        for (columnName, value) in row { 
         let recipe = Recipe(code: value as! String, title: "Title") 
         recipes.append(recipe) 
         } 
        } 
       } 
// prints all recipes. Everything is perfect 

     for i in self.recipes{ 
      print(i.code) 
     } 
      client.disconnect() 
     } 
//prints nothing. recipe.count = 0 

     for i in self.recipes{ 
      print(i.code) 
     } 
    } 
} 

func error(error: String!, code: Int32, severity: Int32) { 
    print(error) 
    } 
} 
+0

"client.connect(" x.x.x "、username:" xx "、パスワード:" xxx "、データベース:" xxx ")"部分の2番目のforループを試してください。言い換えれば、getRecipeFromDB関数の最後の "}"の直前に2番目のforループを入れてみてください。 – DevB2F

答えて

1

深いコピーを必要とするので、これは思っています。ファンクション内のクロージャは順番に実行されていないので、クロージャ付きファンクションの直後にデータを読み取るべきではありません(ファンクションの次のステートメントの前にクロージャが実行される保証はありません)。目標をアーカイブするには、completionクロージャを使用する必要があります。

func getRecipeFromDB(completion: ([Recipe]) -> Void){ 

    let client = SQLClient.sharedInstance() as! SQLClient 

    client.connect("x.x.x.x", username: "xx", password: "xxx", database: "xxx") { 
     success in 
     client.execute("SELECT item FROM TABLE") { 
      results in 

      for table in results as! [[[String:AnyObject]]] { 
       for row in table { 

        for (columnName, value) in row { 
         let recipe = Recipe(code: value as! String, title: "Title") 
         recipes.append(recipe) 
        } 
       } 
      } 
      // prints all recipes. Everything is perfect 

      for i in self.recipes{ 
       print(i.code) 
      } 
      client.disconnect() 

      // This is important to invoke the callback when reading data is done 
      completion(self.recipes) 
     } 
    } 
} 

// Call your query data with a completion 
getRecipeFromDB { 
    (data) in 
    for i in data{ 
     print(i.code) 
    } 
} 
+0

メッセージをありがとう。私はこのコードを試しました。できます。私はデータにアクセスすることができますが、私はレシピアレイにデータを書き込むことができません。まだ空です。 {{データ self.viewModel.recipes.append(:i.recipeCode!recipeTitle:!レシピ(recipeCode i.recipeTitle))におけるiに対する で (データ) }} –

+0

getRecipeFromDB –

+0

あなたは 'data'を意味します'getRecipeFromDB'関数の空白は何ですか? – Enix

関連する問題