你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS文檔序列化(對象歸檔)

iOS文檔序列化(對象歸檔)

編輯:IOS開發綜合

對象歸檔:

概念:

對象歸檔是指將對象寫入文件保存在硬盤,當再次重新打開程序時,可以還原這些對象。也稱:對象序列化、對象持久化。


數據持久性的方式(其實就是3類)

1,NSKeyedArchiver——對象歸檔

2,NSUserDefaults 3,屬性列表

4,SQLite數據庫 5,Core Data數據庫


歸檔方式:

對Foundation庫中對象進行歸檔

自定義對象進行歸檔(需要實現歸檔協議,NSCoding)


歸檔與屬性列表的區別:

1,歸檔後的文件是加密的,屬性列表是明文的。

2,屬性列表不能存儲自定義對象類型,歸檔可以。



代碼實現:

//對象歸檔,對象反歸檔
int main(int argc, char * argv[])
{
    @autoreleasepool {
//        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
        //歸檔(序列化)
        NSArray *array = @[@"abc",@"123",@1234];
        
        NSString *homePath = NSHomeDirectory();
        NSLog(@"homePath :%@",homePath);
        NSString *path = [homePath stringByAppendingPathComponent:@"test.archive"];  //文件和擴展名隨便取
        
        BOOL success = [NSKeyedArchiver archiveRootObject:array toFile:path];
        if (success) {
            NSLog(@"archive success");
        }
    }
    return 0;
}


這是就生成了一個加密文件。

打開

6270 6c69 7374 3030 d401 0203 0405 081c
1d54 2474 6f70 5824 6f62 6a65 6374 7358
2476 6572 7369 6f6e 5924 6172 6368 6976
6572 d106 0754 726f 6f74 8001 a609 0a12
1314 1555 246e 756c 6cd2 0b0c 0d0e 5624
636c 6173 735a 4e53 2e6f 626a 6563 7473
8005 a30f 1011 8002 8003 8004 5361 6263
5331 3233 1104 d2d2 1617 181b 5824 636c
6173 7365 735a 2463 6c61 7373 6e61 6d65
a219 1a57 4e53 4172 7261 7958 4e53 4f62
6a65 6374 574e 5341 7272 6179 1200 0186
a05f 100f 4e53 4b65 7965 6441 7263 6869
7665 7208 1116 1f28 3235 3a3c 4349 4e55
6062 6668 6a6c 7074 777c 8590 939b a4ac
b100 0000 0000 0001 0100 0000 0000 0000
1e00 0000 0000 0000 0000 0000 0000 0000


int main(int argc, char * argv[])
{
    @autoreleasepool {
//        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
        //歸檔(序列化)
//        NSArray *array = @[@"abc",@"123",@1234];
//        
//        NSString *homePath = NSHomeDirectory();
//        NSLog(@"homePath :%@",homePath);
//        NSString *path = [homePath stringByAppendingPathComponent:@"test.archive"];  //文件和擴展名隨便取
//        
//        BOOL success = [NSKeyedArchiver archiveRootObject:array toFile:path];
//        if (success) {
//            NSLog(@"archive success");
//        }
        
        //解歸檔(反序列化)
        NSString *homePath = NSHomeDirectory();
        NSString *path = [homePath stringByAppendingPathComponent:@"test.archive"];
        NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        NSLog(@"NSKeyedUnarchiver:%@",array);
    }
    return 0;
}


這個方法的缺陷:

一個對象歸檔成一個文件,當對象非常多時非常麻煩。

下面的方式可以解決這個問題:

歸檔:

1,使用NSData實例作為歸檔的存儲數據

2,添加歸檔的內容(設置key和value)

3,完成歸檔

4,將歸檔數據存入磁盤中


解歸檔:

1,從磁盤中讀取文件,生成NSData實例

2,根據Data實例創建和初始化解歸檔實例

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



  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved