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]
How can i store in sqlite3
or in NSUserDefaults
如何在sqlite3或NSUserDefaults中存储
i have tried like this
我试过这样
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 个解决方案
#1
1
For NSUserDefaults:
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)
}
Note: Don't expect the correct result when testing this in a playground.
注意:在操场上测试时不要期望得到正确的结果。
#1
1
For NSUserDefaults:
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)
}
Note: Don't expect the correct result when testing this in a playground.
注意:在操场上测试时不要期望得到正确的结果。