0

I have a collection of objects with different classes A, B, and C (all share a common superclass):

// Encoded collection
@[A, B, C]

This collection gets archived and unarchived via NSCoding. Is there a way to partially unarchive this collection if one of the classes has since been removed from the project?

It seems decodeObjectForKey: fails and returns a nil object when it encounters an object it can't decode. Is there a way to instead only get what is able to be decoded? I understand why this behavior makes sense for an object but not for a collection.

// Expected decoding when A class definition is missing:
@[B, C]

// Actual:
nil
Warpling
  • 2,024
  • 2
  • 22
  • 38

1 Answers1

1

If the class name and the class that you want to use instead are known then you can use the setClass:forClassName: method of NSKeyedUnArchiver to specify a translation, so you could use something like [unarchiver setClass:MySuperClass.class forClassName:@"C"]

Claus Jørgensen
  • 25,882
  • 9
  • 87
  • 150
Paulw11
  • 108,386
  • 14
  • 159
  • 186
  • What if it's not a migration but a hard depreciation with a removal of the Class being unarchived? Could I attempt to `setClass` using the the removed classes superclass? – Warpling Feb 11 '16 at 01:55
  • Yes, that is what I have shown in my answer - `MySuperClass` will be instantiated for any `Class C` objects in the archive – Paulw11 Feb 11 '16 at 01:56
  • Is there a way to do this without knowing the specific classes that may not be recognized? My issue is with older builds receiving an archive with an object from a newer build which uses a class the older build won't recognize. – Warpling Feb 11 '16 at 03:56
  • 1
    No. You either need to ensure that your newer code explicitly handles older archives by adding a translation when you remove the deprecated class or simply keep the deprecated classes around but don't use them; Backward compatibility is why use of deprecated APIs is typically a warning and not an error – Paulw11 Feb 11 '16 at 03:58
  • Okay, thank you, that makes sense. Sounds like what I want to do isn't possible with a collection. (._.) – Warpling Feb 11 '16 at 04:15