Object serialization
Object serialization (or object archival in Objective-C terminology), in computing, is the conversion of a object in object-oriented programming to a regular, architecture-dependent structure such as a stream that can be easily stored in a file or other storage device, or piped to another application, and can be easily reconstructed.
Several programming languages support serialization, such as Smalltalk, Objective-C, Java and .NET.
Objective-C Example
The following Objective-C example demonstrates object serialization achieved by overriding the write: and read: methods in the Object root class (NB this is in the GNU runtime variant of Objective-C, in the NeXT-style runtime, the implementation is near identical).
Sender class
The following code defines a Sender class to demonstrate the construction of an object and the method and result of serialization (or archival, as is usual Objective-C terminology). The Sender class stores the time (as per time in the C standard library), and contains methods to convert the class to a TypedStream.
If we were to compile the class below, and run it, the program would send the stream representing the object the standard output, for example GNU TypedStream 1D@îC¡
Sender.h
#import <objc/Object.h> #import <stdio.h> #import <time.h>
@interface Sender : Object { int current_time; }
- (id) set; - (id) send; - (id) write: (TypedStream *) s; - (id) read: (TypedStream *) s; @end
Sender.m
#import "Sender.h" @implementation Sender
- (id) set { current_time = time(NULL); //set the time }
- (id) write: (TypedStream *) s { [super write:s]; // write necessary information in Sender's superclass // so we can reconstruct it objc_write_types(s, "i", ¤t_time); // write the current_time variable. // the "i" specifies an integer, multiple variables // can be specified as per @encode. return self; }
- (id) read: (TypedStream *) s { [super read:s]; // read back the superclass information objc_read_types(s, "i", ¤t_time); // write back the types we need.
return self; }
- (id) send { //A convenience class to output the stream to standard output. TypedStream *s =objc_open_typed_stream(stdout, OBJC_WRITEONLY); [self write:s]; objc_close_typed_stream(s); } @end
int main(void) { Sender *s = [Sender new]; [s set]; //set the time [s send];
return 0; }