0

I would like to serialize excerpts from a collection of objects that do not themselves conform to NSCoding to a file. What's the best way to achieve this without transformation the collected objects an intermediary representation (one that would conform to NSCoding)? The (apparent) problem arises, because NSKeyedArchiver requires unique keys, and there is no NSArchiver on iOS.

For instance, the following will not work, because values are overwritten inside the loop as keys are reused. Calculating unique key strings from some loop index would be possible but quite a nuisance:

for (MyObject *object in myObjects) {
    NSString *someString = myObject.someString; // excerpted string

    [archiver encodeObject: someString withKey: @"someString"]
}
Drux
  • 11,992
  • 13
  • 66
  • 116

2 Answers2

0

One way would be to encode the extracted excepts as an array:

NSMutableArray *extractedStrings = [NSMutableArray array];
for (MyObject *object in myObjects) {
    [extractedStrings addObject:object.someString];
}
[archiver encodeObject:extractedStrings forKey:@"extractedStrings"];
Stuart
  • 36,683
  • 19
  • 101
  • 139
  • Tx. That's what I would call an intermediate representation. I real life I am dealing with several fields (not just single strings), so it gets relatively messy. – Drux Mar 23 '15 at 10:55
0

Adding a category that conforms to NSCoding has proved to be the best solution in this case:

@interface MyClass (Coding) <NSCoding>
// ...
Drux
  • 11,992
  • 13
  • 66
  • 116