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:
@interfaceMyClass: Object {AnotherClass*obj;inti; } ...@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 [superwrite:stream]; 3 objc_write_types(stream, "@i",obj, &i); 4returnself; 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access