swift - 'UnsafePointer<UInt8>' 的初始化导致悬空指针

标签 swift xcode swift5

尝试清除我的 SWIFT 5/XCODE 项目中的一些警告,但我陷入了困境:

 let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]
 let msgData = Data(bytes: UnsafePointer<UInt8>(sendBytes), count: sendBytes.count)
 socket.write(msgData, withTimeout: -1.0, tag: 0)
 socket.readData(withTimeout: -1.0, tag: 0)
        

对于“UnsafePointer”,我收到以下警告和两条建议:

“UnsafePointer”的初始化导致悬空指针

  1. 从“[UInt8]”到“UnsafePointer”的隐式参数转换生成的指针仅在调用“init(_:)”期间有效

  2. 在数组上使用“withUnsafeBufferPointer”方法,以便将参数显式转换为对定义范围有效的缓冲区指针

这是我的解决方案,更好吗?

版本 1:

let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]
let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: sendBytes.count)
uint8Pointer.initialize(from: sendBytes, count: sendBytes.count)
let msgData = Data(bytes: uint8Pointer, count: sendBytes.count)
socket.write(msgData, withTimeout: -1.0, tag: 0)
socket.readData(withTimeout: -1.0, tag: 0)

版本 2:

let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]                     
let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: sendBytes.count)
uint8Pointer.initialize(from: sendBytes, count: sendBytes.count)
let msgData = Data(bytes: uint8Pointer, count: sendBytes.count)
socket.write(msgData, withTimeout: -1.0, tag: 0)
socket.readData(withTimeout: -1.0, tag: 0)
uint8Pointer.deallocate()

最佳答案

自 Swift 3 起,可以简单地使用 UInt8 数组初始化 Data 实例。

let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]
let msgData = Data(sendBytes)

关于swift - 'UnsafePointer<UInt8>' 的初始化导致悬空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62618048/

相关文章:

swift - ModelIO/MDLAsset 是短视吗?

iphone - 在 iPhone 的应用程序中访问本地短信数据

iphone - Xcode 组织者 : can not use iPhone (dyld_shared_cache_extract_dylibs failed)

ios - UITableViewHeaderFooterView 不支持 nib 中的自动布局约束

ios - Card simpleDescription() 在 Apple 的 swift 示例中不起作用

swift - 确实在索引路径中选择了用户,然后向 UI Collection View Controller 显示了用户详细信息

ios - RPBroadcastSampleHandler 任何方法未被调用

ios - Swift 5 : Why swift 5 update ask to forcibly unwrap the label. 字体?

swift - CoreData SwiftUI TextField - 将绑定(bind)数据类型更改为 Double 不起作用

iOS 9.1 由于 APAddressBook 书籍而崩溃(未找到图片)