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]
如何存储在sqlite3
或NSUserDefaults
我试过这样的
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)
答案 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)
}
注意:在游乐场测试时,不要指望正确的结果。