持久化 归档

//

//  User.h

//  YLEX

//

//  Created by yelon on 15-4-1.

//  Copyright (c) 2015 yelon. All rights reserved.

 

//

 

@interface User : NSObject<NSCoding>

@property(nonatomic,strong) NSString *name;
@property(nonatomic,assign) NSUInteger age;
+ (id)user:(NSString *)name age:(NSUInteger)age;
+ (void)saveArchive;
+ (void)printInfo;
@end

#define filePath [NSTemporaryDirectory() stringByAppendingPathComponent:@"user"]
@implementation User
@synthesize name = _name;
@synthesize age = _age;

+(id)user:(NSString *)name age:(NSUInteger)age{

    User *user = [[User alloc]init];
    user.name = name;
    user.age  = age;
    return YL_AutoRelease(user);
}

+(void)saveArchive{

    NSMutableData *data = [[NSMutableData alloc]init];
    NSKeyedArchiver *archvier = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archvier encodeObject:[User user:@"晏龙" age:27] forKey:@"1"];
    [archvier encodeObject:[User user:@"晏•龙" age:28] forKey:@"2"];
    [archvier encodeObject:[User user:@"yanlong 30" age:29] forKey:@"4"];
    //    [archvier encodeRootObject:self];
    [archvier finishEncoding];
   
    NSLog(@"filePath == %@",filePath);
    BOOL flag = [data writeToFile:filePath atomically:YES];
    NSLog(@"%@",flag?@"yes":@"no");
}

+(void)printInfo{

    NSLog(@"filePath == %@",filePath);
    NSError *error;
    NSMutableData *arData = [[NSMutableData alloc]initWithContentsOfFile:filePath];
    NSLog(@"error == %@",error);
    NSKeyedUnarchiver *unArchvier = [[NSKeyedUnarchiver alloc]initForReadingWithData:arData];
    User *user = nil;
    user = [unArchvier decodeObjectForKey:@"1"];
    NSLog(@"1 == %@,%d",[user name],[user age]);
    user = [unArchvier decodeObjectForKey:@"2"];
    NSLog(@"2 == %@,%d",[user name],[user age]);
    user = [unArchvier decodeObjectForKey:@"3"];
    NSLog(@"3 == %@,%d",[user name],[user age]);
    user = [unArchvier decodeObjectForKey:@"4"];
    NSLog(@"4 == %@,%d",[user name],[user age]);
}

-(void)encodeWithCoder:(NSCoder *)aCoder{

    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeInteger:_age forKey:@"age"];
}

-(id)initWithCoder:(NSCoder *)aDecoder{

    if (self = [super init]) {
       
        _name = [aDecoder decodeObjectForKey:@"name"];
        _age = [aDecoder decodeIntegerForKey:@"age"];
    }
    return self;
}
-(void)dealloc{

    self.name = nil;
    YL_SuperDealloc;
}

 

你可能感兴趣的:(持久化)