这里是 Android 开发者和 iOS 新手。我有一个要迁移到 iOS 的应用程序。我正在同时学习 Xcode 和 Swift,所以请温柔点! :)
我的问题是我只想保存/检索如下类(Java 中):
public class CardDeck implements Parcelable{
private ArrayList<Profile> cards;
private int location;
public CardDeck(){
this.cards = new ArrayList<>();
this.location = 0;
//this.numCards = 0;
}
public CardDeck(ArrayList<Profile> cards) {
this.cards = cards;
this.location = 0;
//this.numCards = cards.size();
}
protected CardDeck(Parcel in) {
cards = in.createTypedArrayList(Profile.CREATOR);
//numCards = in.readInt();
location = in.readInt();
}
}
我想保存/检索包含配置文件数组的 CardDeck 对象。我的初步阅读让我认为您不能使用 UserDefaults 或 NSCoding 执行此操作,因为 plist 文件不能包含像配置文件这样的自定义数据类型。我做对了吗? UserDefaults 适用于标准数据类型(bool、int、String 等),NSCoding 可以处理自定义对象,例如 CardDeck,但 CardDeck 只能包含标准数据类型的成员。
专业人士会如何处理我的问题?核心数据?
我在 Android 中使用 SharedPreferences
和 Gson.toJson(cardDeck)
处理了这个问题。
感谢阅读!
最佳答案
CoreData 是一个建立在 SQLLite 之上的 ORM。听起来这对你想要的东西来说可能有点矫枉过正。
您可以只声明您的类 Codable:
CardDeck 类:可编码 {
然后只需使用 JSONEncoder、JSONDecoder 将它们编码和解码为 Data 对象,这些对象可以转换为 String,然后存储在文件或用户首选项中。 CardDeck 中的任何自定义类型也需要是 JSONCodeable。
JSONCodeable 是一种协议(protocol)(即 Java 术语中的接口(interface)),可以作为现有类的扩展实现(不能在 Java 中执行此操作,但在 C# 中可以)。
关于iOS Xcode 如何使用包含自定义对象的自定义对象来保存数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52280503/