简体   繁体   English

如何在Swift中使用NSCoding保存Int64变量数组

[英]How to save an array of Int64 variables using NSCoding in Swift

I am currently using NSCoding to save an array of Int variables like this: 我目前正在使用NSCoding保存这样的Int变量数组:

var myArray = [Int]()

myArray = aDecoder.decodeObjectForKey("MyArray") as! [(Int)]

aCoder.encodeObject(myArray, forKey: "MyArray")

I now need to save an array of Int64 variables. 现在,我需要保存一个Int64变量数组。 I thought it would be simple, so I did this: 我认为这很简单,所以我这样做了:

var myNewArray = [Int64]()

myNewArray = aDecoder.decodeObjectForKey("MyNewArray") as! [(Int64)]

aCoder.encodeObject(myNewArray, forKey: "MyNewArray")

However I get an error on the last line: Cannot convert value of type '[Int64]' to expected argument type 'AnyObject?' 但是,我在最后一行收到错误:无法将类型[Int64]的值转换为预期的参数类型'AnyObject?

I am puzzled as to why it works with Int but not Int64. 我不知道为什么它可以与Int一起使用,而不与Int64一起使用。 How can I achieve this? 我该如何实现?

I am puzzled as to why it works with Int but not Int64. 我不知道为什么它可以与Int一起使用,而不与Int64一起使用。 How can I achieve this? 我该如何实现?

It doesn't actually work with Int either. 它实际上也不适用于Int。 You have to have an array of Objective-C objects , and a number is not an object in Objective-C. 您必须具有一个Objective-C 对象数组,并且数字不是Objective-C中的对象。

However, Swift bridges Int to NSNumber automatically, so it looks like it works. 但是,Swift自动将Int 接到NSNumber,因此看起来可以正常工作。

It doesn't do that for Int64. 对于Int64,它不这样做。 You have to create the NSNumber objects yourself. 您必须自己创建NSNumber对象。

In the current version of Swift, when you convert [Int] to AnyObject (or AnyObject? ), Swift generates NSArray containing NSNumber s. 在当前版本的Swift中,当您将[Int]转换为AnyObject (或AnyObject? )时,Swift会生成包含NSNumberNSArray Although NSNumber can contain Int64 ( long long int in C/Objective-C), Swift does not convert Int64 to NSNumber automatically, thus, [Int64] cannot be automatically converted to AnyObject . 尽管NSNumber可以包含Int64 (在C / Objective-C中为long long int ),但是Swift不会自动将Int64转换为NSNumber ,因此[Int64]无法自动转换为AnyObject

You can generate an NSArray containing NSNumber explicitly. 您可以显式生成一个包含NSNumberNSArray

let myI64Array = aDecoder.decodeObjectForKey("MyNewArray") as! [NSNumber]
myNewArray = myI64Array.map{$0.longLongValue}

Or: 要么:

let myI64Array = myNewArray.map{NSNumber(longLong: $0)}
aCoder.encodeObject(myI64Array, forKey: "MyNewArray")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM