Archiving Objects

Saving and restoring objects is made easier by Objective-C’s facilities for reflection —inspecting at runtime the structure of instances and classes. Objects can be pre-designed at build-time, encoded, and saved as resources for reconstruction at runtime. The runtime state of objects can similarly be saved and restored in documents or other files. An object’s values are stored along with type information necessary to restore a fully functioning instance.

Archiving Descendants of Object

To save and restore descendants of Object, you can use its methods -write : and -read :, along with some functions provided by the runtime and a helper class called TypedStream .

For example, suppose your class declares an interface like this:

@interface 
               MyClass : Object {
  AnotherClass* obj;
  int 
               i;
}
...
@end

To add the fields that MyClass declares to a stream that will be written to an archive, implement the following method:

1 -(id)write:(TypedStream*)stream { 
2   [super write:stream];
3   objc_write_types(stream, "@i", obj, &i);
4   return 
               self;
5 }

Line 1. Override the root class method -write:.

Line 2. Call the parent class method to write the fields declared in the parent.

Line 3. Call the runtime function objc_write_types( ) . The second parameter is a concatenation of descriptors for the types of fields you are writing. These are one-character strings, the same as those used by the @encode directive. They are listed in objc-api.h.

To read the fields of MyClass from a stream that has been ...

Get Objective-C Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.