gpt4 book ai didi

swift3 - 将 NSUUID 转换为 UnsafePointer

转载 作者:行者123 更新时间:2023-12-01 15:23:41 25 4
gpt4 key购买 nike

随着 Swift 3 的更新,getUUIDBytesgetBytesUUID 对象上似乎都不可用。

let uuid = UIDevice.current.identifierForVendor
let mutableUUIDData = NSMutableData(length:16)
uuid.getBytes(UnsafeMutablePointer(mutableUUIDData!.mutableBytes))
// ^^^ compiler error, value of type UUID? has no member getBytes

即使 getBytes 在文档中被列为 UUID 上的方法,我也会收到此错误:https://developer.apple.com/reference/foundation/nsuuid/1411420-getbytes

最佳答案

一个正确的方法:

let uuid = UIDevice.current.identifierForVendor!
var rawUuid = uuid.uuid

withUnsafePointer(to: &rawUuid) {rawUuidPtr in //<- `rawUuidPtr` is of type `UnsafePointer<uuid_t>`.
rawUuidPtr.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<uuid_t>.size) {bytes in
//Use `bytes` only in this closure. (Do NEVER export `bytes` out of the closure.)
print(bytes[0],bytes[1])
//...
}
}

另一种正确的做法:

withUnsafePointer(to: &rawUuid) {rawUuidPtr in //<- `rawUuidPtr` is of type `UnsafePointer<uuid_t>`.
let bytes = UnsafeRawPointer(rawUuidPtr).assumingMemoryBound(to: UInt8.self)
//Use `bytes` only in this closure. (Do NEVER export `bytes` out of the closure.)
print(bytes[0],bytes[1])
//...
}

正如 Rob 已经评论过的,完全不能保证导出传递给 withUnsafeBytes 闭包参数的指针。上下文的轻微变化(32 位/64 位、x86/ARM、调试/发布、添加看似不相关的代码...)会使您的应用崩溃。

还有一个更重要的是,uuidString的UTF-8 DataNSUUID.getBytes的字节序列是完全不同的:

let nsUuid = uuid as NSUUID //<-Using the same `UUID`

let mutableUUIDData = NSMutableData(length:16)!
nsUuid.getBytes(mutableUUIDData.mutableBytes.assumingMemoryBound(to: UInt8.self))
print(mutableUUIDData) //-><1682ed24 09224178 a279b44b 5a4944f4>

let uuidData = uuid.uuidString.data(using: .utf8)!
print(uuidData as NSData) //-><31363832 45443234 2d303932 322d3431 37382d41 3237392d 42343442 35413439 34344634>

关于swift3 - 将 NSUUID 转换为 UnsafePointer<UInt8>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39907603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com