Swift枚举和NSCoding [英] Swift enum and NSCoding

查看:149
本文介绍了Swift枚举和NSCoding的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有String属性和NSImage属性的'Thing'对象; Thing类具有encodeWithCoder:和decodeWithCoder:方法,我可以使用NSKeyedArchiver / Unarchiver归档和取消存档[Thing]数组。



到目前为止,这么好。现在我想通过一系列方向来扩展我的Thing类,其中'Direction'是以下枚举:

 枚举方向{ 

case North(direction:String)
case东(direction:String)
case南(direction:String)
case西(direction:String)

}

换句话说,我希望存储的数据是

  thing1.directions:Direction = [.North(thing2),.Suth(thing3)] 

(在一个更完美的世界中,我将直接引用我的东西而不是他们的名字,但我意识到这将很容易创建引用循环 - 在创建Thing之前,无法设置引用另一个Thing - 所以我将禁止,我正在寻找一种快速而肮脏的方法来保存我的应用程序数据并继续。)



由于我将需要其他地方的指示,这是一个单独的实体,而不仅仅是Thing类中的枚举。 (不知道这是否有所作为)。



使我的方向枚举符合NSCoding的最佳方式是什么?
我可以想出的最好的解决方法是创建一个[String:String]字典,North和South作为键,thing2和thing3作为值,并重建我的枚举属性,但有更好的方法吗?
为此,有没有办法使元组符合NSCoding,因为现在(String,String)让我不兼容协议AnyObject'错误。



非常感谢

解决方案

我所做的是给枚举一个类型,并对其原始值进行编码和解码,否则实现描述为枚举,并对该字符串进行编码和解码。无论哪种方式(或者使用其他方法),您显然需要一种在枚举器和可归档类型之间的双向转换方法。


I have a 'Thing' object with a String property and an NSImage property; the Thing class has encodeWithCoder: and decodeWithCoder: methods, and I can archive and unarchive a [Thing] array using NSKeyedArchiver/Unarchiver.

So far, so good. Now I want to expand my Thing class by an array of directions, where 'Direction' is the following enum:

enum Direction{

case North(direction:String)
case East(direction:String)
case South(direction:String)
case West(direction:String)

}

In other words, the data I wish to store is

thing1.directions: Direction = [.North("thing2"), .South("thing3")]

(In a more perfect world, I'd be using direct references to my Things rather than just their names, but I realise that this will easily create reference cycles - can't set a reference to another Thing until that Thing has been created - so I'll refrain. I'm looking for a quick and dirty method to save my app data and move on.)

Since I will be needing directions elsewhere, this is a separate entity, not just an enum inside the Thing class. (Not sure whether that makes a difference.)

What is the best way to make my Direction enum conform to NSCoding? The best workaround I can come up with involves creating a [String: String] dictionary with "North" and "South" as keys and "thing2" and "thing3" as values, and reconstruct my enum property from that, but is there a better way? And for that matter, is there a way to make tuples conform to NSCoding because right now (String, String) gets me a 'not compatible to protocol "AnyObject"' error.

Many thanks.

解决方案

What I do is give the enum a type and encode and decode its raw value, or else implement description for the enum and encode and decode that string. Either way (or if you use some other way), you obviously need a way to convert in both directions between an enumerator and an archivable type.

这篇关于Swift枚举和NSCoding的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆