Objective-c中對象的歸檔

來源:互聯網
上載者:User

   對象的歸檔是指將對象寫入檔案儲存在硬碟上,當再次擋開程式的時候,可以還原這些對象。對象的歸檔也叫對象的序列化或對象的持久化

資料的持久性儲存的方式:

      1、對象歸檔NSKeyedArchiver

       2、NSUserDefaults

      3、屬性列表化(NSArray,NSDictionary)

      4、SQLite資料庫、Core Data資料庫

歸檔的形式:

    1、對Foundation庫中對象進行歸檔    2、自訂對象歸檔,自訂對象進行歸檔需要實現歸檔協議NSCoding

1、下面來實現第一種形式的歸檔,實現數組的序列化與還原序列化

歸檔

       //實現一個數組的序列化與還原序列化        NSString *homeDirectory = NSHomeDirectory();//擷取使用者的根目錄        NSArray *array = @[@123,@456,@"789",@"88888"];                NSString *drectory = [homeDirectory stringByAppendingPathComponent:@"array.archive"];        BOOL isSuccess = [NSKeyedArchiver archiveRootObject:array toFile:drectory];        if(isSuccess){            NSLog(@"成功序列化........");        }

解檔

//解歸檔,還原序列化    NSArray *array1 = [NSKeyedUnarchiver unarchiveObjectWithFile:drectory];        NSLog(@"%@",array1);

使用這種方法的歸檔的缺點是每個對象都要歸檔一個檔案,對象多歸檔的檔案也多,

自訂內容歸檔(該種方法的歸檔使用的更方便)

   歸檔

       使用NSData執行個體作為作為歸檔的儲存資料

       添加歸檔的內容(設定key與value)

       完成歸檔

       將歸檔資料存入磁碟中

   解歸檔

       從磁碟讀取檔案,產生NSData執行個體

       根據Data執行個體建立和初始化解歸檔執行個體

       解歸檔,根據key訪問value的值

//歸檔        NSString *homeDirectory = NSHomeDirectory();        NSString *filePath = [homeDirectory stringByAppendingPathComponent:@"customMsg.archive"];        NSMutableData *data = [NSMutableData data];        NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];                [archiver encodeInt:1000 forKey:@"num"];        [archiver encodeObject:@"jimGreen" forKey:@"name"];        [archiver finishEncoding];        [archiver release];        [data writeToFile:filePath atomically:YES];

//解歸檔        NSData *myData = [NSData dataWithContentsOfFile:filePath];        NSKeyedArchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:myData];        int num = [unarchiver decodeIntForKey:@"num"];        NSString *name = [unarchiver decodeObjectForKey:@"name"];                NSLog(@"name id %@,age is %d",name,num);

2、自訂對象歸檔

自訂的對象要支援歸檔,需要實現NSCoding協議,NSCoding協議有兩個方法encodeWithCoder方法對對象的屬性資料進行編碼處理,initWithCoder解碼歸檔資料來初始化對象。

 實現NSCoding協議後就能用NSKeyedArchiver就行歸檔。

下面看個例子:

對User類進行解歸檔

.h檔案

#import <Foundation/Foundation.h>@interface User : NSObject<NSCoding>@property(nonatomic,copy)NSString *name;@property(nonatomic,copy)NSString *email;@property(nonatomic,copy)NSString *password;@property(nonatomic,assign)int age;@end

.m檔案

#import "User.h"@implementation User//對屬性進行編碼,歸檔的時候會調用-(void)encodeWithCoder:(NSCoder *)aCoder{        [aCoder encodeInt:_age forKey:@"age"];    [aCoder encodeObject:_email forKey:@"email"];    [aCoder encodeObject:_name forKey:@"name"];    [aCoder encodeObject:_password forKey:@"password"];}//對屬性進行解碼,解檔的時候會用-(id)initWithCoder:(NSCoder *)aDecoder{     if(self = [super init]){                _age = [aDecoder decodeIntForKey:@"age"];        self.name = [aDecoder decodeObjectForKey:@"name"];        self.email = [aDecoder decodeObjectForKey:@"email"];        self.password = [aDecoder decodeObjectForKey:@"password"];    }    return self;}//該方法是當在以%@格式列印對象的時候調用-(NSString *)description{        NSString *str = [NSString stringWithFormat:@"name is %@,age id %d,email is %@,password id %@",_name,_age,_email,_password];        return str;}-(void)dealloc{    [_password release];    [_email release];    [_name release];    [super dealloc];}@end

main檔案中的歸檔

    User *user = [[User alloc]init];        user.age = 24;        user.name = @"jim Green";        user.email = @"jim@qq.com";        user.password = @"123456";                NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"user.archive"];        BOOL isSuccess = [NSKeyedArchiver archiveRootObject:user toFile:path];        if (isSuccess) {            NSLog(@"成功!");                    [user release];                //自訂對象的解歸檔                                }

解檔

User *user = [NSKeyedUnarchiver unarchiveObjectWithFile:path];            NSLog(@"%@",user);            

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.