iOS 数据的本地存储-自定义对象的归档

释放双眼,带上耳机,听听看~!

对于自定义类型的对象,也是可以使用(NSKeyedArchiver NSKeyedUnarchiver)进行归档和解归档的,要定义的对象遵守NSCoding协议并实现该协议的:

-(void)encodeWithCoder:(NSCoder *)aCoder和-(id)initWithCoder:(NSCoder *)aDecoder方法即可,比较简单,直接上代码:

//.h

@interface CustomObject :
NSObject<NSCoding>

@property(strong,
nonatomic) NSString* name;

@property(assign,
nonatomic) int age;

@end




//.m

//归档

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

    [aCoder encodeObject:self.name forKey:@"name"];

    [aCoder encodeObject:[NSNumbernumberWithInt:self.age]forKey:@"age"];

}




//解归档

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

    if (self = [superinit]) {

        self.name = [aDecoder decodeObjectForKey:@"name"];

        self.age = ((NSNumber*)[aDecoder decodeObjectForKey:@"age"]).intValue;

    }

    return
self;

}

//仅仅打印对象,跟归档没直接关系

-(NSString *)description{

    return [NSStringstringWithFormat:@"name:
%@, age: %i",self.name,self.age];

}




现在可以把CustomObject当做NSString一样使用归档了。

CustomObject *object = [[CustomObject alloc]init];

object.name = @"jim";

object.age = 25;




//归档操作

NSArray *docmentPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

NSString *stringPath = [docmentPath
objectAtIndex:0];

NSString *fileName = [stringPath
stringByAppendingPathComponent:@"archiveFile.plist"];

[NSKeyedArchiver archiveRootObject:object toFile: fileName];

 //解归档,验证数据归档是否成功

object = [NSKeyedUnarchiver
unarchiveObjectWithFile: fileName];

NSLog(@"%@",object);

 

 

人已赞赏
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索