简体   繁体   English

iOS Xcode 如何使用包含自定义对象的自定义对象保存数据?

[英]iOS Xcode How to persist data with custom objects containing custom objects?

Android developer and iOS newb here. Android 开发人员和 iOS 新手在这里。 I have an app I'm migrating to iOS.我有一个要迁移到 iOS 的应用程序。 I'm learning Xcode and Swift at the same time so be gentle please!我正在同时学习 Xcode 和 Swift,所以请保持温和! :) :)

My question is I simply want to save/retrieve a class such as below (in Java):我的问题是我只想保存/检索如下类(在 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();
  }
}

I would like to save/retrieve a CardDeck object that contains an Array of Profiles.我想保存/检索包含配置文件数组的 CardDeck 对象。 My initial readings makes me think you cannot do this with either UserDefaults or NSCoding because plist files cannot contain a custom data type like Profile.我最初的阅读让我觉得你不能用 UserDefaults 或 NSCoding 来做到这一点,因为 plist 文件不能包含像 Profile 这样的自定义数据类型。 Did I get that right?我做对了吗? UserDefaults are for standard data types (bool, int, String, etc.) and NSCoding can handle a custom object such as CardDeck BUT CardDeck can only have members that are standard data types. UserDefaults 适用于标准数据类型(bool、int、String 等)并且 NSCoding 可以处理自定义对象,例如 CardDeck 但 CardDeck 只能具有标准数据类型的成员。

How would you pros handle my problem?你们专业人士如何处理我的问题? Core Data?核心数据?

I handled this in Android by using SharedPreferences and Gson.toJson(cardDeck) .我在 Android 中使用SharedPreferencesGson.toJson(cardDeck)处理了这个问题。

Thanks for reading!谢谢阅读!

CoreData is an ORM built on top of SQLLite. CoreData 是一个建立在 SQLLite 之上的 ORM。 It sounds like it might be overkill for what you want.听起来对于你想要的东西来说可能有点矫枉过正。

You could just declare your classes Codable:您可以将您的类声明为 Codable:

class CardDeck : Codable { }类 CardDeck : Codable { }

Then just use JSONEncoder, JSONDecoder to encode and decode them to Data objects which can be converted to String and then stored in a file or user preferences.然后只需使用 JSONEncoder、JSONDecoder 将它们编码和解码为 Data 对象,这些对象可以转换为 String 然后存储在文件或用户首选项中。 Any custom types in CardDeck will also need to be JSONCodeable. CardDeck 中的任何自定义类型也需要是 JSONCodeable。

JSONCodeable is a protocol (ie Interface in Java terms) and can be implemented as an extension on an existing class (can't do this in Java, sort of can in C#). JSONCodeable 是一种协议(即 Java 术语中的接口)并且可以作为现有类的扩展来实现(在 Java 中不能这样做,在 C# 中可以这样做)。

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

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