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);

}

相關文章
相關標籤/搜索