ios HTML 持久化存储,iOS-初级数据持久化_复杂对象的存储-自定义Student类

0c2bd2f943fb048fcf018c2e7a12359c.png

2dd136311b2dbb1c70098792898c1bdd.png

cf638ff71b6d3ff0c128ebe88e773616.png

adaff684d3ea0d1539e94105273d85a1.png

5eab435741d01d100b911ec064b92656.png

//

// ViewController.m

// 初级数据持久化_复杂对象的存储-自定义Student类

//

// Created by YIem on 16/3/2.

// Copyright © 2016年 YIem. All rights reserved.

//

import "ViewController.h"

import "Student.h"

@interface ViewController ()

@end

@implementation ViewController(void)viewDidLoad {[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

self.view.backgroundColor = [UIColor greenColor];

NSString *fileStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

Student *stu = [[Student alloc] init];

stu.name = @"YIem";

stu.sex = @"男";

stu.age = 21;

stu.score = 0.1;

NSString *stuPath = [fileStr stringByAppendingPathComponent:@"/stu.aaa"];

// 存储复杂类型数据要进行归档 读取进行反归档

// 归档时会调用NSConding协议方法, 需要在Student类中实现

// 参数1: 内容

// 参数2: 文件

[NSKeyedArchiver archiveRootObject:stu toFile:stuPath];

// 反归档

Student *backStu = [NSKeyedUnarchiver unarchiveObjectWithFile:stuPath];

NSLog(@"姓名: %@ 性别: %@ 年龄: %ld 分数: %.1f", backStu.name, backStu.sex, backStu.age, backStu.score);

}

(void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end

//

// Student.h

// 初级数据持久化_复杂对象的存储

//

// Created by YIem on 16/3/2.

// Copyright © 2016年 YIem. All rights reserved.

//

import

import

@interface Student : NSObject

@property (nonatomic, copy) NSString *name;

@property (nonatomic, copy) NSString *sex;

@property (nonatomic, assign) NSInteger age;

@property (nonatomic, assign) CGFloat score;

@end

//

// Student.m

// 初级数据持久化_复杂对象的存储

//

// Created by YIem on 16/3/2.

// Copyright © 2016年 YIem. All rights reserved.

//

import "Student.h"

@implementation Student(void)dealloc

{[_name release];

[_sex release];

[super dealloc];

}

(void)encodeWithCoder:(NSCoder *)aCoder

{[aCoder encodeObject:self.name forKey:@"name"];

[aCoder encodeObject:self.sex forKey:@"sex"];

// *注意: 不同类型数据应用不同方法

// key可以不与属性同名, 仅仅用来供反归档时对应

[aCoder encodeInteger:self.age forKey:@"age"];

[aCoder encodeDouble:self.score forKey:@"score"];

}

// 用与上面同名(instancetype)initWithCoder:(NSCoder *)aDecoder

{

self = [super init];

if (self) {self.name = [aDecoder decodeObjectForKey:@"name"];

self.sex = [aDecoder decodeObjectForKey:@"sex"];

self.age = [aDecoder decodeIntegerForKey:@"age"];

self.score = [aDecoder decodeDoubleForKey:@"score"];

}

return self;

}

@end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值