我在swift的sqlite表中得到了错误的值

时间:2015-07-02 05:45:43

标签: swift sqlite

我从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"

1 个答案:

答案 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")
 }