您的位置:首页 > 移动开发 > IOS开发

【深入浅出ios开发】存储一般的数据对象

2015-03-30 14:49 417 查看
一般通过NSKeyedArchiver来存储一般的对象:

重点在encode和decode

存储数据:

[objc] view
plaincopy

- (IBAction)save:(id)sender {  

    MrPerson *person = [[MrPerson alloc]init];  

    person.name = @"Ranran";  

    person.age = 16;  

    person.height = 1.62;  

    [NSKeyedArchiver archiveRootObject:person toFile:@"/Users/misaka/Desktop/0410/p.Data"];  

      

}  

读取数据:

[objc] view
plaincopy

- (IBAction)read:(id)sender {  

      

    MrPerson *person = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/misaka/Desktop/0410/p.Data"];  

      

    NSLog(@"%@---%ld-----%f",person.name,(long)person.age,person.height);  

      

}  

Person类头文件中的设置:

[objc] view
plaincopy

#import <Foundation/Foundation.h>  

  

@interface MrPerson : NSObject<NSCoding>  

@property (nonatomic,copy) NSString* name;  

@property (nonatomic,assign) NSInteger age;  

@property (nonatomic,assign) double height;  

@end  

Person类实现文件中的设置:

[objc] view
plaincopy

#import "MrPerson.h"  

  

@implementation MrPerson  

- (void)encodeWithCoder:(NSCoder *)aCoder  

{  

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

    [aCoder encodeInteger:self.age forKey:@"age"];  

    [aCoder encodeDouble:self.height forKey:@"height"];  

}  

  

- (id)initWithCoder:(NSCoder *)aDecoder  

{  

    if (self = [super init]) {  

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

     self.age  =   [aDecoder decodeIntegerForKey:@"age"];  

     self.height =    [aDecoder decodeDoubleForKey:@"height"];  

    }  

    return self;  

}  

@end  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐