Anonymous user
Object serialization: Difference between revisions
m
→{{header|Objective-C}}: modernize
No edit summary |
m (→{{header|Objective-C}}: modernize) |
||
Line 1,124:
int numberOfLegs;
}
- (
- (void) dump;
@end
@implementation Animal
- (
{
if ((self = [super init])) {
Line 1,139 ⟶ 1,136:
}
return self;
}
- (void) dump
Line 1,170 ⟶ 1,162:
NSMutableArray *eatenList;
}
- (
- (void) addEatenThing: (NSString*)thing;
@end
@implementation Mammal
- (
{
if ((self = [super init])) {
Line 1,187 ⟶ 1,175:
return self;
}
- (
{
if ((self = [super initWithName: name andLegs: 4])) {
Line 1,198 ⟶ 1,186:
{
[eatenList addObject: thing];
}
- (void) dump
Line 1,208 ⟶ 1,191:
[super dump];
NSLog(@"has fur? %@", (hasFur) ? @"yes" : @"no" );
NSLog(@"it has eaten %d things:", [eatenList count]);
for ( id element in eatenList )
NSLog(@"it has eaten a %@", element);
NSLog(@"end of eaten things list");
Line 1,228 ⟶ 1,207:
if ((self = [super initWithCoder: coder])) {
hasFur = [coder decodeBoolForKey: @"Mammal.hasFur"];
eatenList =
}
return self;
Line 1,237 ⟶ 1,216:
int main()
{
@autoreleasepool {
// let us create a fantasy animal
Animal *anAnimal = [[Animal alloc]
initWithName: @"Eptohippos"
andLegs: 7
];
// for some reason an Eptohippos is not an horse with 7 legs,
// and it is not a mammal, of course...
// let us create a fantasy mammal (which is an animal too)
Mammal *aMammal = [[Mammal alloc]
initWithName: @"Mammaluc"
hasFur: YES
];
// let us add some eaten stuff...
[aMammal addEatenThing: @"lamb"];
[aMammal addEatenThing: @"table"];
[aMammal addEatenThing: @"web page"];
// dump anAnimal
NSLog(@"----- original Animal -----");
[anAnimal dump];
// dump aMammal...
NSLog(@"----- original Mammal -----");
[aMammal dump];
// now let us store the objects...
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *arch = [[NSKeyedArchiver alloc]
initForWritingWithMutableData: data];
[arch encodeObject: anAnimal forKey: @"Eptohippos"];
[arch encodeObject: aMammal forKey: @"Mammaluc"];
[arch finishEncoding];▼
[data writeToFile: @"objects.dat" atomically: YES];▼
▲ [arch finishEncoding];
▲ [data writeToFile: @"objects.dat" atomically: YES];
// now we want to retrieve the saved objects...
NSData *ldata = [[NSData alloc]
initWithContentsOfFile: @"objects.dat"];
NSKeyedUnarchived *darch = [[NSKeyedUnarchiver alloc]
initForReadingWithData: ldata];
Animal *archivedAnimal = [darch decodeObjectForKey: @"Eptohippos"];
Mammal *archivedMammal = [darch decodeObjectForKey: @"Mammaluc"];
[darch finishDecoding];
// now let's dump/print the objects...
NSLog(@"\n");
NSLog(@"----- the archived Animal -----");
[archivedAnimal dump];
NSLog(@"----- the archived Mammal -----");
[archivedMammal dump];
}
return EXIT_SUCCESS;
}</lang>
|