Create an Array in Swift from an NSData Object

后端 未结 4 1060
说谎
说谎 2020-12-13 09:13

I\'m trying to store an array of integers to disk in swift. I can get them into an NSData object to store, but getting them back out into an array is difficult. I can get

4条回答
  •  别那么骄傲
    2020-12-13 10:00

    It's also possible to do this using an UnsafeBufferPointer, which is essentially an "array pointer", as it implements the Sequence protocol:

    let data = NSData(/* ... */)
    
    // Have to cast the pointer to the right size
    let pointer = UnsafePointer(data.bytes)
    let count = data.length / 4
    
    // Get our buffer pointer and make an array out of it
    let buffer = UnsafeBufferPointer(start:pointer, count:count)
    let array = [UInt32](buffer)
    

    This eliminates the need for initializing an empty array with duplicated elements first, to then overwrite it, although I have no idea if it's any faster. As it uses the Sequence protocol this implies iteration rather than fast memory copy, though I don't know if it's optimized when passed a buffer pointer. Then again, I'm not sure how fast the "create an empty array with X identical elements" initializer is either.

提交回复
热议问题