如何在swift中使用BLOB将字节数组[UInt8]存储和检索到sqlite3数据库中?

时间:2016-05-04 11:16:48

标签: ios swift sqlite nsuserdefaults

let arr: [UInt8] =  [0x14, 0x00, 0xAB, 0x45, 0x49, 0x1F, 0xEF, 0x15, 0xA8, 0x89, 0x78, 0x0F, 0x09, 0xA9, 0x07, 0xB0, 0x01, 0x20, 0x01, 0x4E, 0x38, 0x32, 0x35, 0x56, 0x20, 0x20, 0x20, 0x00]

如何存储在sqlite3NSUserDefaults

我试过这样的

 let arrData = NSData(bytes: &arr, length: (arr?.count)!)

 let d = NSUserDefaults.standardUserDefaults()
 d.setObject(arrData, forKey: "mydata")
 d.synchronize()

 let obj = d.objectForKey("mydata")
 let objData = obj as! NSData
 let resultArr = NSKeyedUnarchiver.unarchiveObjectWithData(objData) as! [UInt8]
 print(resultArr.count)

1 个答案:

答案 0 :(得分:1)

对于NSUserDefaults:

let integersToStore: [UInt8] = [0x14, 0x00, 0xAB, 0x45, 0x49, 0x1F, 0xEF, 0x15, 0xA8, 0x89, 0x78, 0x0F, 0x09, 0xA9, 0x07, 0xB0, 0x01, 0x20, 0x01, 0x4E, 0x38, 0x32, 0x35, 0x56, 0x20, 0x20, 0x20, 0x00]

let dataToStore = NSData(bytes: integersToStore, length: integersToStore.count)

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(dataToStore, forKey: "mydata")
defaults.synchronize()

// get the data we stored in NSUserDefaults
if let readData = defaults.dataForKey("mydata") {

    // determine the number of UInt8 to read from this data
    let count = readData.length / sizeof(UInt8)

    // create a new UInt8 array with the correct count
    var readArray = [UInt8](count: count, repeatedValue: 0)

    // copy data into array
    readData.getBytes(&readArray, length: count * sizeof(UInt8))

    // readArray has what you need
    print(readArray)
}

注意:在游乐场测试时,不要指望正确的结果。