Swift Data.SubData使用exc_bad_instruction(代码= exc_i386_invop,s



我正在尝试从 data 对象检索数据子集。当我尝试使用 subdata(in:)获取数据时,我会得到上述错误。我无法弄清楚我在做什么错误,因为所有值看起来都正确。所讨论的代码是:

let tempData = incomingDataBuffer.subdata(in: 0..<headerSizeInBytes)

使用我已经调查的LLDB,发现一切看起来都正确。

(lldb) po incomingDataBuffer.count
8
(lldb) po headerSizeInBytes
6
(lldb) po incomingDataBuffer
▿ 8 bytes
  - count : 8
  ▿ pointer : 0x0000600000002a42
    - pointerValue : 105553116277314
  ▿ bytes : 8 elements
    - 0 : 17
    - 1 : 6
    - 2 : 29
    - 3 : 49
    - 4 : 2
    - 5 : 0
    - 6 : 1
    - 7 : 6
(lldb) po incomingDataBuffer.subdata(in: 0..<headerSizeInBytes)
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
The process has been returned to the state before expression evaluation.

这对我没有任何意义。所有值看起来都正确。没有什么是无。我为什么要失败?感谢帮助。:)

Data值(或一般集合)的索引不一定基于零。A slice 与原始数据共享索引。示例:

let buffer = Data(bytes: [1, 2, 3, 4, 5, 6])[2..<4]
print(buffer.count) // 2
print(buffer.indices) // 2..<4
let tmpData = buffer.subdata(in: 0..<2)
// 💣 Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

因此,您必须考虑开始索引:

let tmpData = buffer[buffer.startIndex ..< buffer.startIndex + 2]
print(tmpData as NSData) // <0304>

或简单地使用前缀

let tmpData = buffer.prefix(2)
print(tmpData as NSData) // <0304>

应用于您的情况:

let tempData = incomingDataBuffer.prefix(headerSizeInBytes)

相关内容

最新更新