利用归档保存数组数据

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

 

posted on 2014-10-09 22:00  MGY007  阅读(262)  评论(0编辑  收藏  举报