objc對象歸檔 序列化

來源:互聯網
上載者:User

NSString、NSArray、NSData、NSDictionary都實現了NSCoding協議,可直接通過調用writeToFile歸檔,那麼OBJC自訂物件類型呢?首先實現NSCoding協議,重寫encodeWithCode方法和initWithCode方法,然後通過NSKeyedArchiver轉換為NSData,然後通過NSData的writeToFile方法寫入到檔案,或者將轉換後的NSData放入到NSArray或NSDictionary中調用writeToFile寫入到檔案便可實現封裝了自訂類型的資料和字典的歸檔;通過NSKeyedUnarchiver讀取歸檔檔案到對象,或者通過NSArray的arrrayWithContentsOfFile或NSDictionary的dictionaryWithContentsOfFile到數組對象或字典,然後取出序列化過的自訂對象(即自訂對象的NSData形式),然後通過NSKeyedUnarchiver反歸檔到對象。


[plain]
------------------------------------------------測試代碼------------------------------------------------  
  
NSString *str = @"hello";  
    [str writeToFile:@"/Users/lili/Desktop/str.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];  
      
    NSArray *arr = [[NSArray alloc]initWithObjects:@"lili",@"tata", nil];  
    [arr writeToFile:@"/Users/lili/Desktop/arr.txt" atomically:YES];  
      
    NSDictionary *dict = [NSDictionary dictionaryWithObjects:@[@"lili",@"男"] forKeys:@[@"name",@"sex"]];  
    [dict writeToFile:@"/Users/lili/Desktop/dict.txt" atomically:YES];  
      
      
    Person *parent = [[Person alloc]init];  
    parent.age = 40;  
    parent.name = @"lili";  
      
    Person *child = [[Person alloc]init];  
    child.age = 22;  
    child.name = @"linian";  
      
    parent.child = child;  
      
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:parent];  
    [data writeToFile:@"/Users/lili/Desktop/data.txt" atomically:YES];  
      
    Person *people = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/lili/Desktop/data.txt"];  
    NSLog(@"%@",people);  
      
    NSDictionary *dictPerson = [NSDictionary dictionaryWithObjects:@[[NSKeyedArchiver archivedDataWithRootObject:parent],[NSKeyedArchiver archivedDataWithRootObject:child]] forKeys:@[@"parent",@"child"]];  
    [dictPerson writeToFile:@"/Users/lili/Desktop/dictPerson.txt" atomically:YES];  
      
    NSDictionary *pdict = [NSDictionary dictionaryWithContentsOfFile:@"/Users/lili/Desktop/dictPerson.txt"];  
    Person *tPerson = [NSKeyedUnarchiver unarchiveObjectWithData:[pdict objectForKey:@"parent"]];  
    NSLog(@"%@",tPerson);  
      
      
      
    NSArray *arrPerson = [[NSArray alloc]initWithObjects:[NSKeyedArchiver archivedDataWithRootObject:parent],[NSKeyedArchiver archivedDataWithRootObject:parent], nil];  
    [arrPerson writeToFile:@"/Users/lili/Desktop/arrPerson.txt" atomically:YES];  
      
    NSArray *pArr = [NSArray arrayWithContentsOfFile:@"/Users/lili/Desktop/arrPerson.txt"];  
    Person *aPerson = [NSKeyedUnarchiver unarchiveObjectWithData:[pArr objectAtIndex:0]];  
    NSLog(@"%@",aPerson);  
  
  
------------------------------------------------Person類------------------------------------------------  
  
#import <Foundation/Foundation.h>  
@interface Person : NSObject<NSCoding>  
@property(strong,nonatomic)Person *child;  
@property(assign,nonatomic)int age;  
@property(copy,nonatomic)NSString *name;  
@end  
  
  
#import "Person.h"  
@implementation Person  
-(NSString *)description  
{  
    return [NSString stringWithFormat:@"{age:%d,name:%@,child:%@}",self.age,self.name,self.child];  
}  
  
-(void)encodeWithCoder:(NSCoder *)aCoder  
{  
    [aCoder encodeInt:self.age forKey:@"age"];  
    [aCoder encodeObject:self.name forKey:@"name"];  
    [aCoder encodeObject:self.child forKey:@"child"];  
}  
  
-(id)initWithCoder:(NSCoder *)aDecoder  
{  
    if(self = [super init]){  
        self.age = [aDecoder decodeIntForKey:@"age"];  
        self.name = [aDecoder decodeObjectForKey:@"name"];  
        self.child = [aDecoder decodeObjectForKey:@"child"];  
    }  
    return self;  
}  
@end  

------------------------------------------------測試代碼------------------------------------------------
 
NSString *str = @"hello";
    [str writeToFile:@"/Users/lili/Desktop/str.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    NSArray *arr = [[NSArray alloc]initWithObjects:@"lili",@"tata", nil];
    [arr writeToFile:@"/Users/lili/Desktop/arr.txt" atomically:YES];
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjects:@[@"lili",@"男"] forKeys:@[@"name",@"sex"]];
    [dict writeToFile:@"/Users/lili/Desktop/dict.txt" atomically:YES];
    
    
    Person *parent = [[Person alloc]init];
    parent.age = 40;
    parent.name = @"lili";
    
    Person *child = [[Person alloc]init];
    child.age = 22;
    child.name = @"linian";
    
    parent.child = child;
    
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:parent];
    [data writeToFile:@"/Users/lili/Desktop/data.txt" atomically:YES];
    
    Person *people = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/lili/Desktop/data.txt"];
    NSLog(@"%@",people);
    
    NSDictionary *dictPerson = [NSDictionary dictionaryWithObjects:@[[NSKeyedArchiver archivedDataWithRootObject:parent],[NSKeyedArchiver archivedDataWithRootObject:child]] forKeys:@[@"parent",@"child"]];
    [dictPerson writeToFile:@"/Users/lili/Desktop/dictPerson.txt" atomically:YES];
    
    NSDictionary *pdict = [NSDictionary dictionaryWithContentsOfFile:@"/Users/lili/Desktop/dictPerson.txt"];
    Person *tPerson = [NSKeyedUnarchiver unarchiveObjectWithData:[pdict objectForKey:@"parent"]];
    NSLog(@"%@",tPerson);
    
    
    
    NSArray *arrPerson = [[NSArray alloc]initWithObjects:[NSKeyedArchiver archivedDataWithRootObject:parent],[NSKeyedArchiver archivedDataWithRootObject:parent], nil];
    [arrPerson writeToFile:@"/Users/lili/Desktop/arrPerson.txt" atomically:YES];
    
    NSArray *pArr = [NSArray arrayWithContentsOfFile:@"/Users/lili/Desktop/arrPerson.txt"];
    Person *aPerson = [NSKeyedUnarchiver unarchiveObjectWithData:[pArr objectAtIndex:0]];
    NSLog(@"%@",aPerson);
 
 
------------------------------------------------Person類------------------------------------------------
 
#import <Foundation/Foundation.h>
@interface Person : NSObject<NSCoding>
@property(strong,nonatomic)Person *child;
@property(assign,nonatomic)int age;
@property(copy,nonatomic)NSString *name;
@end
 
 
#import "Person.h"
@implementation Person
-(NSString *)description
{
    return [NSString stringWithFormat:@"{age:%d,name:%@,child:%@}",self.age,self.name,self.child];
}
 
-(void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeInt:self.age forKey:@"age"];
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.child forKey:@"child"];
}
 
-(id)initWithCoder:(NSCoder *)aDecoder
{
    if(self = [super init]){
        self.age = [aDecoder decodeIntForKey:@"age"];
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.child = [aDecoder decodeObjectForKey:@"child"];
    }
    return self;
}
@end

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.