11. Программирование на Objective-C. Архивация объектов



#import <Foundation/Foundation.h>


@interface Car : NSObject {
    @private
    NSString *name;
    float engCap;
}

@property (retain) NSString *name;
@property float engCap;

@end


@implementation Car

@synthesize name;
@synthesize engCap;

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:name forKey:@"name"];
    [aCoder encodeObject:[NSNumber numberWithFloat:engCap] forKey:@"engCap"];
}

- initWithCoder:(NSCoder *)aCoder
{
#if !__has_feature(objc_arc)
    name = [[aCoder decodeObjectForKey:@"name"] retain];
#else
    name = [aCoder decodeObjectForKey:@"name"];
#endif
    engCap = [[aCoder decodeObjectForKey:@"engCap"] floatValue];
    return self;
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"The engine capacity of %@ is %f liter", name, engCap];
}

@end


int main(int argc, const char * argv[])
{
    @autoreleasepool
    {
        Car *kamaz =  [[Car alloc] init];
        [kamaz setName:@"Kamaz"];
        [kamaz setEngCap:10.8f];
        [NSKeyedArchiver archiveRootObject:kamaz toFile:@"/Users/Abbas/Documents/kamaz.plist"];
        NSLog(@"%@", kamaz);
        
        Car *newKamaz = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/Abbas/Documents/kamaz.plist"];
        NSLog(@"%@", newKamaz);
    }
    return 0;
}