将Float数组写入二进制文件并在swift中读取

时间:2015-11-19 20:30:55

标签: ios arrays swift binaryfiles

如何将Float数组写入二进制文件然后读取?

var array: [Float]: [0.1, 0.2, 0.3]

func writeArrayToBinary(array: [Float]) {
    //...
}

func readArrayFromBinary() -> [Float] {
    //...
}

2 个答案:

答案 0 :(得分:5)

请试试这个......

var array: [Float] = [0.1, 0.2, 0.3]

func writeArrayToPlist(array: [Float]) {
    if let arrayPath: String = createArrayPath() {
        (array as NSArray).writeToFile(arrayPath, atomically: false)
    }
}

func readArrayFromPlist() -> [Float]? {
    if let arrayPath: String = createArrayPath() {
        if let arrayFromFile: [Float] = NSArray(contentsOfFile: arrayPath) as? [Float] {
            return arrayFromFile
        }
    }
    return nil
}

func createArrayPath () -> String? {
    if let docsPath: String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last {
        return ((docsPath as NSString).stringByAppendingPathComponent("myArrayFileName") as NSString).stringByAppendingPathExtension("plist")
    }
    return nil
}

答案 1 :(得分:4)

正如您在评论中所说,速度是优先考虑的因素。然后,我建议你使用Cocoa提供的Data类将数组写入二进制文件。

<强>代码:

let url = URL(fileURLWithPath: "myTestFile.myBinExt")

// Writing
var wArray: [Float] = [1.1, 3.7, 2.5, 6.4, 7.8]
let wData = Data(bytes: &wArray, count: wArray.count * MemoryLayout<Float>.stride)
try! wData.write(to: url)

// Reading file
let rData = try! Data(contentsOf: url)

// Converting data, version 1
var rArray: [Float]?

rData.withUnsafeBytes { (bytes: UnsafePointer<Float>) in
    rArray = Array(UnsafeBufferPointer(start: bytes, count: rData.count / MemoryLayout<Float>.size))
}

print(rArray!)

// Converting data, version 2
let tPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: rData.count)
rData.copyBytes(to: tPointer, count: rData.count)

defer {
    tPointer.deinitialize(count: rData.count)
    tPointer.deallocate(capacity: rData.count)
}

var pointer = UnsafeRawPointer(tPointer) // Performs no allocation or copying; no deallocation shall be done.

// MemoryLayout<Float>.size = 4
print(pointer.load(fromByteOffset: 00, as: Float.self))
print(pointer.load(fromByteOffset: 04, as: Float.self))
print(pointer.load(fromByteOffset: 08, as: Float.self))
print(pointer.load(fromByteOffset: 12, as: Float.self))
print(pointer.load(fromByteOffset: 16, as: Float.self))

<强>输出:

[1.10000002, 3.70000005, 2.5, 6.4000001, 7.80000019]
1.1
3.7
2.5
6.4
7.8