您的位置:首页 > 其它

6 归档解档(自定义对象数据存储)

2015-09-25 23:45 453 查看
#import <Foundation/Foundation.h>

//记得要遵守<NSCoding>协议

>  @interface person : NSObject<NSCoding>  @property(nonatomic,copy)NSString *name;  @property(nonatomic,assign)int age;  @end


#import "person.h"

@implementation person
-(void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:_name forKey:@"name"];
[aCoder encodeInt:_age forKey:@"age"];
}
-(id)initWithCoder:(NSCoder *)aDecoder{
if (self =[super init]) {
_name =[aDecoder decodeObjectForKey:@"name"];
_age =[aDecoder decodeIntForKey:@"age"];
}

return self;
}
@end


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end


#import "ViewController.h"
#import "person.h"
@interface ViewController ()

@end

@implementation ViewController
//存数据
- (IBAction)save:(id)sender {
//获取临近的目录
NSString *tmpPath =NSTemporaryDirectory();
NSString *filePath =[tmpPath stringByAppendingPathComponent:@"person.data"];
person *p =[[person alloc] init];
p.name =@"天桥";
p.age =18;
[NSKeyedArchiver archiveRootObject:p toFile:filePath];
}
//取数据
- (IBAction)read:(id)sender {
NSString *tmpPath =NSTemporaryDirectory();
NSString *filePath =[tmpPath stringByAppendingPathComponent:@"person.data"];

//记得给解档属性进行赋值
person * p  =  [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%@,%d",p.name,p.age);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: