Use archive to save array data

Source: Internet
Author: User

1. First, create a model class and follow the nscoding agreement.

 

@interface Contact : NSObject <NSCoding>@property (nonatomic, copy) NSString *name;@property (nonatomic, copy) NSString *phone;@endimplementation 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. Test Archiving

@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

 

Use archive to save array data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.