码迷,mamicode.com
首页 > 其他好文 > 详细

利用归档保存数组数据

时间:2014-10-09 22:49:51      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   strong   文件   数据   

1首先创建一个模型类,一定要遵守NSCoding协意。

 

@interface Contact : NSObject <NSCoding>

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *phone;

@end

implementation Contact

- (void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:self.name forKey:@"name"];//读取时属性对应的Key
    [encoder encodeObject:self.phone forKey:@"phone"];
}

- (id)initWithCoder:(NSCoder *)decoder
{
    if (self = [super init]) {
        self.name = [decoder decodeObjectForKey:@"name"]; //归档时属性对应的Key
        self.phone = [decoder decodeObjectForKey:@"phone"];
    }
    return self;
}
@end

 

2测试归档

@interface ContactsTest : UITableViewController

@property (nonatomic, strong) NSMutableArray *array

@end


@implementation MJContactsViewController

-(void)writ{


  //创建归档文件路径。“contacts.data”可以随便写
   NSString *path=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"contacts.data"]

 // 归档数组
  [NSKeyedArchiver archiveRootObject:self. array toFile: path];
 
}


-(void)read{
      
     NSString *path=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"contacts.data"]
    
       self.array = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
 
}



@end

 

利用归档保存数组数据

标签:style   blog   color   io   ar   for   strong   文件   数据   

原文地址:http://www.cnblogs.com/mgy007/p/4014562.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!