天天看點

IOS學習筆記二十四(NSData歸檔多個對象和歸檔對象實作深複制)

1、NSData歸檔多個對象

一、之前我寫的學習筆記都是歸檔一個對象,如果需要歸檔多個對象我們需要借助NSData

二、步驟

     1)、NSMutableData作為參數,建構 NSKeyedArchiver對象

     2)、調用NSKeyedArchiver的encodeXXX

     3)、調用NSKeyedArchiver的finishEncoding方法

     4)、NSMutableData儲存到檔案

2、歸檔對象實作深複制

  我們知道深複制就是複制對象和原始對象沒有任何公用的部分,修改複制對象的值不會對原始對象産生影響。

步驟

1)、NSKeyedArchiver的archivedDataWithRootObject

2)、NSKeyedUnarchiver的unarchiveObjectWithData

3、實作Demo

 IApple.h

#import <Foundation/Foundation.h>
#ifndef IApple_h
#define IApple_h
@interface IApple : NSObject <NSCoding>
@property (nonatomic, copy) NSString *color;
@property (nonatomic, assign) double weight;
@property (nonatomic, assign) int size;
-(id)initWithColor:(NSString *) color weight:(double) weight size:(int) size;
@end
 
#endif /* IApple_h */      

IApple.m

#import  "IApple.h"
#import <Foundation/Foundation.h>
@implementation IApple
@synthesize color = _color;
@synthesize weight = _weight;
@synthesize size = _size;
-(id)initWithColor:(NSString *) color weight:(double) weight size:(int) size
{
    if (self = [super init])
    {
        self.color = color;
        self.weight = weight;
        self.size = size;
    }
    return self;
}
-(NSString *)description
{
    return [NSString stringWithFormat:@"<IApple [color = %@, weight = %g, _size = %d]>", self.color, self.weight, self.size];
}
 
-(void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:_color forKey:@"color"];
    [aCoder encodeDouble:_weight forKey:@"weight"];
    [aCoder encodeInt:_size forKey:@"size"];
}
-(id) initWithCoder:(NSCoder *)aDecoder
{
    _color = [aDecoder decodeObjectForKey:@"color"];
    _weight = [aDecoder decodeDoubleForKey:@"weight"];
    _size = [aDecoder decodeIntForKey:@"size"];
    return self;
}
 
@end      
#import  "IApple.h"
#import <Foundation/Foundation.h>
@implementation IApple
@synthesize color = _color;
@synthesize weight = _weight;
@synthesize size = _size;
-(id)initWithColor:(NSString *) color weight:(double) weight size:(int) size
{
    if (self = [super init])
    {
        self.color = color;
        self.weight = weight;
        self.size = size;
    }
    return self;
}
-(NSString *)description
{
    return [NSString stringWithFormat:@"<IApple [color = %@, weight = %g, _size = %d]>", self.color, self.weight, self.size];
}
 
-(void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:_color forKey:@"color"];
    [aCoder encodeDouble:_weight forKey:@"weight"];
    [aCoder encodeInt:_size forKey:@"size"];
}
-(id) initWithCoder:(NSCoder *)aDecoder
{
    _color = [aDecoder decodeObjectForKey:@"color"];
    _weight = [aDecoder decodeDoubleForKey:@"weight"];
    _size = [aDecoder decodeIntForKey:@"size"];
    return self;
}
 
@end      

main.m

#import "IApple.h"
int main(int argc, char * argv[]) {
    @autoreleasepool {
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:80], @"java", [NSNumber numberWithInt:90], @"c", [NSNumber numberWithInt:70], @"oc", [NSNumber numberWithInt:100], @"c++",nil];
        NSSet *set = [NSSet setWithObjects:@"java", @"ios", @"c++", @"oc", nil];
        IApple *apple = [[IApple alloc] initWithColor:@"red" weight:50 size:20];
        
        NSMutableData *data = [NSMutableData data];
        NSKeyedArchiver *arch = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
        //歸檔對象
        [arch encodeObject:dict forKey:@"dict"];
        [arch encodeObject:set forKey:@"set"];
        [arch encodeObject:apple forKey:@"apple"];
        //結束歸檔
        [arch finishEncoding];
    
        //在document目錄下建立一個chenyu.txt空檔案
        NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [docPaths objectAtIndex:0];
        NSLog(@"document path:%@", path);
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *chenyuPath = [path stringByAppendingPathComponent:@"chenyu.txt"];
        BOOL isSuccess = [fileManager createFileAtPath:chenyuPath contents:nil attributes:nil];
        if (isSuccess) {
            NSLog(@"make chenyu.txt success");
        } else {
            NSLog(@"make chenyu.txt fail");
        }
        
        //歸檔對象到chenyu.txt檔案
        if([data writeToFile:chenyuPath atomically:YES] == YES)
        {
            NSLog(@"歸檔對象成功");
        }
        else
        {
            NSLog(@"歸檔對象失敗");
        }
        
        //讀取歸檔對象
        NSData *readData = [NSData dataWithContentsOfFile:chenyuPath];
        NSKeyedUnarchiver *unArch = [[NSKeyedUnarchiver alloc] initForReadingWithData:readData];
        NSDictionary *readDict = [unArch decodeObjectForKey:@"dict"];
        NSSet *readSet = [unArch decodeObjectForKey:@"set"];
        NSSet *readApple = [unArch decodeObjectForKey:@"apple"];
        NSLog(@"readDict is:%@", readDict);
        NSLog(@"readSet is:%@", readSet);
        NSLog(@"readApple is %@", readApple);
        
        //使用歸檔對戲實作深複制 深複制就是複制對象和本身對象沒有任何公用部分,是以修改複制對象的屬性不會影響原始對象的屬性
        NSDictionary *diction = [NSDictionary dictionaryWithObjectsAndKeys:[[IApple alloc] initWithColor:@"red" weight:50 size:20], @"one", [[IApple alloc] initWithColor:@"green" weight:60 size:21], @"two", nil];
        //對象歸檔
        NSData *data1 = [NSKeyedArchiver archivedDataWithRootObject:diction];
        //回複對象
        NSDictionary *dictCopy = [NSKeyedUnarchiver unarchiveObjectWithData:data1];
        IApple *app = [dictCopy objectForKey:@"one"];
        [app setColor:@"green"];
        IApple *app1 = [diction objectForKey:@"one"];
        NSLog(@"app1 color is:%@", app1.color);
    }
}      

4、運作結果

2018-07-22 19:34:11.258816+0800 cyTest[62704:16613816] document path:*****/3FF9B833-FAF8-4C30-A855-3D40A4EAE8A6/data/Containers/Data/Application/6AD520C9-3A99-45B5-A2F9-4E4D7CA77486/Documents
2018-07-22 19:34:11.269539+0800 cyTest[62704:16613816] make chenyu.txt success
2018-07-22 19:34:11.271898+0800 cyTest[62704:16613816] 歸檔對象成功
2018-07-22 19:34:11.272976+0800 cyTest[62704:16613816] readDict is:{
    c = 90;
    "c++" = 100;
    java = 80;
    oc = 70;
}
2018-07-22 19:34:11.273243+0800 cyTest[62704:16613816] readSet is:{(
    "c++",
    java,
    ios,
    oc
)}
2018-07-22 19:34:11.273602+0800 cyTest[62704:16613816] readApple is <IApple [color = red, weight = 50, _size = 20]>
2018-07-22 19:34:11.274150+0800 cyTest[62704:16613816] app1 color is:red      

繼續閱讀