2

Android developer and iOS newb here. I have an app I'm migrating to iOS. I'm learning Xcode and Swift at the same time so be gentle please! :)

My question is I simply want to save/retrieve a class such as below (in 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. 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. 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.

How would you pros handle my problem? Core Data?

I handled this in Android by using SharedPreferences and Gson.toJson(cardDeck).

Thanks for reading!

Blazej SLEBODA
  • 8,936
  • 7
  • 53
  • 93

1 Answers1

2

CoreData is an ORM built on top of SQLLite. It sounds like it might be overkill for what you want.

You could just declare your classes Codable:

class 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. Any custom types in CardDeck will also need to be JSONCodeable.

JSONCodeable is a protocol (i.e. 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#).

ADG
  • 343
  • 1
  • 9
  • Thanks Andrew! I'll look into JSONCodable. Sounds like exactly what I need. So grateful. Thanks again. Found it on cocoapods. – lil_matthew Sep 11 '18 at 17:35
  • 1
    Oh! I see now that you don't have to use the Pod. You can use JSONEncoder/decoder is a part of the Codable interface in Swift 4. – lil_matthew Sep 11 '18 at 17:58
  • 1
    Yes, that is correct. JSONCodable is a Swift 4 feature. – ADG Sep 11 '18 at 18:01