OC多个对象的归档和解归档

FJStudent.h

#import <Foundation/Foundation.h>数组


@interface FJStudent : NSObject <NSCoding>dom


@property (nonatomic,copy) NSString *name;工具


@property (nonatomic,assign) int score;atom




@end spa


FJStudent.m.net

#import "FJStudent.h"3d


@implementation FJStudentcode

- (void)encodeWithCoder:(NSCoder *)aCoder{orm

    

    [aCoder encodeObject:_name forKey:@"name"];对象

    

    [aCoder encodeInt:_score forKey:@"score"];

    

}



- (instancetype ) initWithCoder:(NSCoder *)aDecoder{

    

    if (self = [super init]) {

        _name = [aDecoder decodeObjectForKey:@"name"];

        _score = [aDecoder decodeIntForKey:@"score"];

    }

    return self;

}



- (NSString *)description{

    return [NSString stringWithFormat:@"%@ %d",_name,_score];

}


@end


main.m

#import <Foundation/Foundation.h>

#import "FJStudent.h"

#define path @"/Users/IOS1601/Desktop/plist文件/student"

void achiver();

void unAchiver();

int main(int argc, const char * argv[]) {

    @autoreleasepool {

        

        achiver();

        unAchiver();

    }

    return 0;

}

#pragma mark -归档

void achiver(){

    

    NSMutableArray *studentArray = [[NSMutableArray alloc]init];

    

    for (int i=0; i<20; i++) {

        

        FJStudent *stu = [[FJStudent alloc] init];

        

        stu.name = [NSString stringWithFormat:@"name%d",i];

        

        stu.score = arc4random() % 56 + 15;

       

        [studentArray addObject:stu];

        

    }

    

//    //=======归档过程1=========

//    //1.建立一个可变的mdata

//    NSMutableData *mdata = [[NSMutableData alloc]init];

//    

//    //2.建立一个归档工具

//    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]

//                                 initForWritingWithMutableData:mdata];

//    

//    //3.归档,将数组进行归档

//    [archiver encodeObject:studentArray forKey:@"array"];

//    

//    //4.关闭归档

//    [archiver finishEncoding];

//    

//    //5.写入本地文件

//    [mdata writeToFile:path atomically:NO];

    

    //=============归档过程2============

    //参数一:须要归档的对象

    //参数二:归档的路径

    [NSKeyedArchiver archiveRootObject:studentArray toFile:path];

    

}

#pragma mark -解归档


void unAchiver(){

//    //=========解归档的过程1=============

//    //1.建立一个NSData

//    NSData *data = [[NSData alloc]initWithContentsOfFile:path];

//    

//    //2.建立一个解归档工具

//    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]

//                                     initForReadingWithData:data];

//    

//    //3.解归档

//    NSArray * studentArray =  [unarchiver

//                               decodeObjectForKey:@"array"];

//    

//    //4.关闭归档工具

//    [unarchiver finishDecoding];

//    

//    NSLog(@"%@",studentArray);

    

    //=========解归档的过程2=============

    //参数:须要解归档文件的路径;

   NSArray *studentArray = [NSKeyedUnarchiver unarchiveObjectWithFile:path];


    NSLog(@"%@",studentArray);

}

相关文章
相关标签/搜索