iOS中歸檔的建立,資料寫入與讀取

來源:互聯網
上載者:User

標籤:

建立一個工程,為ViewController。

建立兩個類為NJperson

NJperson.h

#import <Foundation/Foundation.h>

// 如果想將一個自訂對象儲存到檔案中必須實現NSCoding協議
@interface NJPerson : NSObject <NSCoding>

@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;
@property (nonatomic, assign) double height;
@end

NJperson.m

#import "NJPerson.h"

@implementation NJPerson


// 當將一個自訂對象儲存到檔案的時候就會調用該方法
// 在該方法中說明如何儲存自訂對象的屬性
// 也就說在該方法中說清楚儲存自訂對象的哪些屬性
- (void)encodeWithCoder:(NSCoder *)encoder
{
    NSLog(@"NJPerson encodeWithCoder");
    [encoder encodeObject:self.name forKey:@"name"];
    [encoder encodeInteger:self.age forKey:@"age"];
    [encoder encodeFloat:self.height forKey:@"heigth"];
}

// 當從檔案中讀取一個對象的時候就會調用該方法
// 在該方法中說明如何讀取儲存在檔案中的對象
// 也就是說在該方法中說清楚怎麼讀取檔案中的對象
- (id)initWithCoder:(NSCoder *)decoder
{
    NSLog(@"NJPerson initWithCoder");
    if (self = [super init]) {
        self.name = [decoder decodeObjectForKey:@"name"];
        self.age = [decoder decodeIntegerForKey:@"age"];
        self.height = [decoder decodeFloatForKey:@"heigth"];
    }
    return self;
}

_______在項目中建立兩個按鈕:一個為save,一個為read。

- (void)saveBtnClick:(id)sender{

 NJStudent *stu = [[NJStudent alloc] init];
    stu.name = @"lnj";
    stu.age = 28;
    stu.height = 1.8;

   // 2.擷取檔案路徑
    NSString *docPath =  [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [docPath stringByAppendingPathComponent:@"stu.xxoo"];
    NSLog(@"path = %@", path);
    
    // 3.將自訂對象儲存到檔案中

    [NSKeyedArchiver archiveRootObject:stu toFile:path];

}


- (void)readBtnClick:(id)sender {

 // 1.擷取檔案路徑
    NSString *docPath =  [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [docPath stringByAppendingPathComponent:@"stu.xxoo"];

    // 2.從檔案中讀取對象
//    NJPerson *p = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    
    NJStudent *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

}

 

iOS中歸檔的建立,資料寫入與讀取

聯繫我們

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