简体   繁体   中英

Issue with UnsafePointer<Uint8> in SQLite project in Swift

We are implementing SQLite in iOS, in Swift, without using wrappers or Objective-C bridging. Everything works fine, except when doing a query and extracting the result. The issue is with the UnsafePointer<UInt8> that is returned from SQLite in Swift as follows:

var querySQL = "SELECT address, phone FROM CONTACTS WHERE NAME = 'myName'"
var cQuery = querySQL.cStringUsingEncoding(NSUTF8StringEncoding)
var statement: COpaquePointer = nil
if sqlite3_prepare_v2(contactsDB, cQuery!, -1, &statement, nil) == SQLITE_OK {
   if sqlite3_step(statement) == SQLITE_ROW {
   var address : UnsafePointer<UInt8> = sqlite3_column_text(statement, 0)
   var data = NSData(bytes: address, length: 10)
   var string = NSString(data: data, encoding: NSUTF8StringEncoding)
   println(string)

As you can see, we can convert the pointer to String if we know the length of the object (in this case 10)

To dig into this issue, I have the following example

let pointerFromString: UnsafePointer<Int8> = "xyz".cStringUsingEncoding(NSUTF8StringEncoding)
let stringFromPointer = String.fromCString(anotherPointerFromString_Int8)                    println(stringFromPointer!)

Given that CChar is an alias of Int8 , I can convert a String to UnsafePointer<Int8> using .cStringUsingEncoding() , and then back to String using .fromCString(<UnsafePointer_CChar>)

The problem is that my SQLite result is a UnsafePointer_UInt8 , that can´t be used with .fromCString()

The bottom line question is: Is it possible to convert or cast a UnsafePointer_UInt8 to UnsafePointer_Int8

This should work:

let address = sqlite3_column_text(statement, 0)
let string = String.fromCString(UnsafePointer<CChar>(address))

Update for Swift 3 (Xcode 8), compare Swift 3: convert a null-terminated UnsafePointer<UInt8> to a string :

let string = String(cString: sqlite3_column_text(statement, 0))

Update:

sqlite3_column_text() returns an implicitly unwrapped optional, and that is why you can pass it to String(cString:) directly.

But according to Column methods, error and NULL handling #41 , the return value can be null (in an out-of-memory situation, or if called with a NULL column type). Therefore it is safer to do

if let text = sqlite3_column_text(statement, 0) {
    let string = String(cString: text)
    // ...
} else {
    // sqlite3_column_text() returned NULL
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM