我从sqlite表中得到了错误的值。这是我的代码
代码:
var arrtribute_Mast_List : NSMutableArray = []
var querySQL = String(format:"SELECT * FROM %@ ORDER BY %@", TABLE_ATTRIBUTE_MASTER, ATTRIBUTE_MASTER_ATTR_ID)
var statement:COpaquePointer = nil
//querySQL = querySQL.String(NSUTF8StringEncoding, allowLossyConversion: false)
if (sqlite3_prepare_v2(database, querySQL, -1, &statement, nil) == SQLITE_OK) {
while(sqlite3_step(statement) == SQLITE_ROW) {
let name = sqlite3_column_text(statement, 2)
let attributeName = String.fromCString(UnsafePointer<CChar>(name))
println("Attribute value = \(attributeName)")
}
sqlite3_finalize(statement);
}
我得到了输出:
Attribute value = Optional("Shamitabh")
需要输出:
Attribute value = "Shamitabh"
答案 0 :(得分:0)
您收到Optional("Shamitabh")
因为String.fromCString
无法保证成功。它可能会失败,attributeName
将为零。您可以通过使其成为隐式解包的可选项来解决此问题(如果String.fromCString
失败将会崩溃):
let attributeName = String.fromCString(UnsafePointer<CChar>(name))!
..或者您可以正确使用并在使用前检查值是否为零。例如,像这样:
if let attributeName = String.fromCString(UnsafePointer<CChar>(name)) {
println("Attribute value = \(attributeName)")
} else {
println("Couldn't get the attribute name")
}