我想将[String]转换为NSData以进行BLE连接。
我知道如何将String转换为NSData / NSData为String。
// String -> NSData
var str: String = "Apple";
let data: NSData = str.dataUsingEncoding(NSUTF8StringEncoding)!
// NSData -> String
var outStr: String = NSString(data:data, encoding:NSUTF8StringEncoding) as! String
但是,如何转换,,
// [String] -> NSData ???
let strs: [String] = ["Apple", "Orange"]
这是转换[UInt8]< - >的示例的NSData https://gist.github.com/nolili/2bf1a701df1015ed6488
我想转换[String]< - > NSData的
// [String] -> NSData ??? Is it correct???
var strs: [String] = ["Apple", "Orange"]
let data2 = NSData(bytes: &strs, length: strs.count)
// NSData -> [String] ... please teach me..
答案 0 :(得分:10)
要直接回答您的问题,您可以询问数组中的每个字符串是否为thisString.dataUsingEncoding(_:)
,并将结果附加到NSMutableData
实例,直到您完成所有操作。
let stringsData = NSMutableData()
for string in strings {
if let stringData = string.dataUsingEncoding(NSUTF16StringEncoding) {
stringsData.appendData(stringData)
} else {
NSLog("Uh oh, trouble!")
}
}
当然,如果您想稍后分离字符串,这对您没有帮助,所以我们真正需要知道的是您打算在什么环境中在连接的另一端使用这些数据?如果另一端也使用Cocoa,请考虑将其打包为PLIST。由于NSString
,NSArray
和NSData
都是属性列表类型,因此您只需直接归档NSArray
NSString
个实例:
let arrayAsPLISTData = NSKeyedArchiver.archivedDataWithRootObject(strings)
...然后将生成的NSData
实例传输到Cocoa感知目标,然后:
if let newStrings: [String] = NSKeyedUnarchiver.unarchiveObjectWithData(arrayAsPLISTData) as? [String] {
// ... do something
}
答案 1 :(得分:5)
我在iOS 9中测试了这个
func test() {
let originalStrings = ["Apple", "Pear", "Orange"]
NSLog("Original Strings: \(originalStrings)")
let encodedStrings = stringArrayToNSData(originalStrings)
let decodedStrings = nsDataToStringArray(encodedStrings)
NSLog("Decoded Strings: \(decodedStrings)")
}
func stringArrayToNSData(array: [String]) -> NSData {
let data = NSMutableData()
let terminator = [0]
for string in array {
if let encodedString = string.dataUsingEncoding(NSUTF8StringEncoding) {
data.appendData(encodedString)
data.appendBytes(terminator, length: 1)
}
else {
NSLog("Cannot encode string \"\(string)\"")
}
}
return data
}
func nsDataToStringArray(data: NSData) -> [String] {
var decodedStrings = [String]()
var stringTerminatorPositions = [Int]()
var currentPosition = 0
data.enumerateByteRangesUsingBlock() {
buffer, range, stop in
let bytes = UnsafePointer<UInt8>(buffer)
for var i = 0; i < range.length; ++i {
if bytes[i] == 0 {
stringTerminatorPositions.append(currentPosition)
}
++currentPosition
}
}
var stringStartPosition = 0
for stringTerminatorPosition in stringTerminatorPositions {
let encodedString = data.subdataWithRange(NSMakeRange(stringStartPosition, stringTerminatorPosition - stringStartPosition))
let decodedString = NSString(data: encodedString, encoding: NSUTF8StringEncoding) as! String
decodedStrings.append(decodedString)
stringStartPosition = stringTerminatorPosition + 1
}
return decodedStrings
}
答案 2 :(得分:1)
Swift 4.2
[String]
-> JSON
-> Data
func stringArrayToData(stringArray: [String]) -> Data? {
return try? JSONSerialization.data(withJSONObject: array, options: [])
}
Data
-> JSON
-> [String]
func dataToStringArray(data: Data) -> [String]? {
return (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String]
}