实际上,我不知道什么是NSMutableDictionary,但似乎我需要它
顺便说一下,我使用xcode 8和swift 2.3。
我从sqlite向这个arry添加一个整数,但是这是错误的 另一个是所有的字符串,所以这里没有问题。
然后,错误就在这里
let recipeIsFavor = sqlite3_column_int(statement, 3)
let recipe_isFavor = Int.fromCString(UnsafePointer<CInt>(recipeIsFavor)) //<--------I wnat to use int here, but I have no idea.
我该怎么做才能编辑这段代码?我希望这个错误可以消失。
func loadData() {
let db_path = NSBundle.mainBundle().pathForResource("Recipes", ofType: "db")
var db = COpaquePointer()
let status = sqlite3_open(db_path!,&db)
if (status == SQLITE_OK) {
print("Open the sqlite success!\n")
}else {
print("Open the sqlite failed!\n")
}
let query_stmt = "SELECT * FROM recipe"
if(sqlite3_prepare_v2(db , query_stmt, -1, &statement, nil) == SQLITE_OK) {
self.data.removeAllObjects()
while (sqlite3_step(statement) == SQLITE_ROW) {
let recipeArray = NSMutableDictionary()
let recipeName = sqlite3_column_text(statement, 0)
let recipe_name = String.fromCString( UnsafePointer<CChar>(recipeName))
let recipeType = sqlite3_column_text(statement, 1)
let recipe_type.......
let recipeImage = sqlite3_column_text(statement, 2)
let recipe_image.......
let recipeIsFavor = sqlite3_column_int(statement, 3)
let recipe_isFavor = Int.fromCString(UnsafePointer<CInt>(recipeIsFavor)) //<--------I wnat to use int here, but I have no idea.
let recipeUserPhoto = sqlite3_column_text(statement, 4)
let recipe_userPhoto....
let recipeUserName = sqlite3_column_text(statement, 5)
let recipe_userName.......
recipeArray.setObject(recipe_name!, forKey: "recipeName")
recipeArray.setObject(recipe_type!, forKey: "recipeType")
recipeArray.setObject(recipe_image!, forKey: "recipeImage")
recipeArray.setObject(recipe_isFavor!, forKey: "recipIsFavor")
recipeArray.setObject(recipe_userPhoto!, forKey: "recipUserPhoto")
recipeArray.setObject(recipe_userName!, forKey: "recipUserName")
data.addObject(recipeArray)
}
sqlite3_finalize(statement)
}else {
print("read the sqlite data failed")
}
}
答案 0 :(得分:0)
sqlite3_column_int()
返回&#34; C整数&#34;在Swift中是Int32
。
要将其转换为Int
,请使用
let recipeIsFavor = sqlite3_column_int(statement, 3)
let recipe_isFavor = Int(recipeIsFavor)
而不是NSMutableDictionary
和NSMutableArray
还使用类型的Swift词典数组
[String: AnyObject]
(或Swift 3中的[String: Any]
),
那么它看起来像这样:
var data: [[String: AnyObject]] = []
let query_stmt = "SELECT * FROM recipe"
if sqlite3_prepare_v2(db , query_stmt, -1, &statement, nil) == SQLITE_OK {
data = []
while (sqlite3_step(statement) == SQLITE_ROW) {
var dict: [String: AnyObject] = [:]
let recipeName = sqlite3_column_text(statement, 0)
let recipe_name = String.fromCString(UnsafePointer<CChar>(recipeName)) ?? ""
let recipeIsFavor = sqlite3_column_int(statement, 3)
let recipe_isFavor = Int(recipeIsFavor)
// ...
dict["recipeName"] = recipe_name
dict["recipIsFavor"] = recipe_isFavor
// ...
data.append(dict)
}
sqlite3_finalize(statement)
} else {
print("read the sqlite data failed")
}