gpt4 book ai didi

ios - 在 Swift 中将向量存储在 NSData 中

转载 作者:行者123 更新时间:2023-11-30 12:05:23 25 4
gpt4 key购买 nike

我不明白为什么下面的代码不起作用:

import Foundation
import SpriteKit

var TestVector: CGVector = CGVector(dx: 1, dy: 1)

var Data: Dictionary<String, Any> = ["abc":CGPoint(x: 0, y: 0), "def":1, "ghi":"Try", "jkl":TestVector]


let DataConverted: Data = NSKeyedArchiver.archivedData(withRootObject: Data)

let DataReceived: Dictionary = (NSKeyedUnarchiver.unarchiveObject(with: DataConverted) as! [String : Any])

抛出的错误是:错误:执行被中断,原因:信号 SIGABRT。进程已留在中断点,使用“thread return -x”返回到表达式求值之前的状态。

对于许多不同类型的数据(String,Int,Double,...),一切都工作正常,但对于向量却不起作用

通过 NSKeyedArchiver 存档的数据类型是否有限制?

谢谢

J.

附加信息:这将用于 MultipeerConnectivy 数据传输

最佳答案

看看 NSValue,它在这个场景中是完美的。

NSValue(cgVector: TestVector)一样添加它,当你从字典中读回它时,只需将它作为CGVector返回,就像这样let vector = cgVectorValue.cgVectorValue

就您而言,您这样做:

var TestVector: CGVector = CGVector(dx: 1, dy: 1)
let vectorValue = NSValue(cgVector: TestVector)

let pointValue = NSValue(cgPoint:CGPoint(x: 0, y: 0))

var Data: Dictionary<String, Any> = ["abc":pointValue, "def":1, "ghi":"Try", "jkl":vectorValue]

let DataConverted: Data = NSKeyedArchiver.archivedData(withRootObject: Data)

let DataReceived: Dictionary = (NSKeyedUnarchiver.unarchiveObject(with: DataConverted) as! [String : Any])

if let vectorValue = DataReceived["jkl"] as? NSValue {
let vector = vectorValue.cgRectValue
}

if let pointValue = DataReceived["abc"] as? NSValue {
let point = vectorValue.cgPointValue
}

苹果一直在使用这个,也许你已经看到当你收到键盘通知时会显示,在 userInfo 字典中你可以使用获取键盘大小

CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size

注意CGRectValue,获取使用NSValue封装的CGRect

来自苹果的文档:

An NSValue object can hold any of the scalar types such as int, float, and char, as well as pointers, structures, and object id references. Use this class to work with such data types in collections (such as NSArray and NSSet), Key-value coding, and other APIs that require Objective-C objects. NSValue objects are always immutable.

更多关于https://developer.apple.com/documentation/foundation/nsvalue

关于ios - 在 Swift 中将向量存储在 NSData 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46731212/

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