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); }
相关文章推荐
- 关于桌面软件的开发语言和开发框架的思考
- 关于桌面软件的开发语言和开发框架的思考
- *LeetCode-Palindrome Partitioning
- java面试题十八 switch一个考题
- hdu 4856 Tunnels (BFS+状压)
- 转:Cygwin下VI命令使用
- 双边滤波
- SpringMVC学习笔记1
- C++求字符串长度
- AnguarJS $apply和$digesty
- 【UIKit-125-4】#import <UIKit/UIViewController.h>
- 创建守护进程
- 单例模板类
- Cortex-M3那点事
- 把图片切割的方法
- More Effective C++ 条款23 考虑使用其他程序库
- HDU 5445 Food Problem、UVa 10163 Storage Keepers、POJ 3260 The Fewest Coins(两次dp)
- C/C++ 中的次方运算
- java面试题十七 switch使用范围
- Android 实现微信,QQ的程序前后台切换:back键切换后台;点击通知栏恢复前台。