您好,欢迎来到二三四教育网。
搜索
您的当前位置:首页将数据写入本地

将数据写入本地

来源:二三四教育网

在iOS中一般将数据写入本地, 可以分为两大类第一类是简单对象 另一类是复杂对象 对于简单对象 我们直接进行写入和获取就可以 对于复杂对象 我们利用的是归档和反归档(归档和反归档是对于复杂对象的存储和获取)

要将数据写入本地 首先我们先来了解一下沙盒(SandBox)
沙盒中包含三个文件夹:

  1. Document(文件文档 用来给用户存储数据的文件夹)
  2. Library(资源 程序员用这个文件夹存储数据信息)
    Library文件夹又包含两个文件夹:
    CaChes(缓存数据的文件夹)
    Preferences(存储用户信息的 例如; NSUserDefaults)
  3. tmp(临时目录 下载的临时文件)

沙盒是由以上三个文件夹组成的 其中Document文件夹就是用户用来存储数据用的 用户将可以将数据存放到这个文件夹里

下面我们来用沙盒存储数据:

  1. 简单数据的存储(字符串 数组 字典 NSData)
    // 字符串的存储
    // 1. 创建沙盒路径
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    // 2. 创建一个字符串 将这个字符串存到 沙盒中
    NSString *str = @"离别是今晚的康桥, I/O file";
    // 3. 拼接字符串路径
    NSString *path = [[pathArray firstObject] stringByAppendingPathComponent:@"poet.txt"];
    NSError *error = nil;
    // 4. 将字符串写入本地
    BOOL isSuc = [str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
    if (isSuc) {
    NSLog(@"存储失败");
    } else {
    NSLog(@"存储成功");
    }
    // 5. 读取字符串
    NSError *readError = nil;
    NSString *readStr = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&readError];
    NSLog(@"%@", readStr);

    // 将数组写入本地
    // 这里 我们就用之前创建的沙盒来做就可以
    NSArray *array = @[@"十年", @"陀飞轮", @"十面埋伏", @"遥远的她"];
    // 拼接数组路径
    NSString *arrayPath = [[pathArray firstObject]stringByAppendingPathComponent:@"musicName.plist"];
    // 将数组写入本地
    BOOL isSuce = [array writeToFile:arrayPath atomically:YES];
    if (isSuce) {
     NSLog(@"存储失败");
    } else {
     NSLog(@"存储成功");
    }
    // 读取数组
    NSArray *array1 = [NSArray arrayWithContentsOfFile:arrayPath];
    NSLog(@"%@", array1);
    
    // 字典写入本地
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"十年", @"陈奕迅", @"大地", @"beyond", @"可乐", @"赵", nil];
    // 拼接字典路径
    NSString *dicPath = [[pathArray firstObject] stringByAppendingPathComponent:@"music.plist"];
    // 将字典写入本地
    BOOL isDic = [dic writeToFile:dicPath atomically:YES];
    if (isDic) {
     NSLog(@"存储成功");
    } else {
     NSLog(@"存储失败");
    }
    // 读出字典
    NSDictionary *secDic = [NSDictionary dictionaryWithContentsOfFile:dicPath];
    NSLog(@"%@", secDic);
    
    // 将NSData类型写入本地
    UIImage *image = [UIImage imageNamed:@"u=881185622,577705802&fm=206&gp=0"];
    // 需要将图转化为二进制(NSData类型)
    // UIImageJPEGRepresentation  UIImagePNGRepresentation(<#UIImage * _Nonnull image#>)
    NSData *imageData = UIImageJPEGRepresentation(image, 0.1);
    // 拼接路径
    NSLog(@"%@", imageData);
    NSString *dataPath = [[pathArray firstObject] stringByAppendingPathComponent:@"image.a"];
    // 写入本地
    BOOL isData = [imageData writeToFile:dataPath atomically:YES];
    if (isData) {
     NSLog(@"写入成功");
    } else {
     NSLog(@"写入失败");
    }
    // 读取NSData
    NSData *newData = [NSData dataWithContentsOfFile:dataPath];
    UIImage *newImage = [UIImage imageWithData:newData];
    NSLog(@"%@", newImage);
    

总结一下 通过上面将数据写入本地的例子可以看出 简单数据写入本地主要分为这几步:
(1) 创建沙盒路径
(2) 创建一个你要存储的对象
(3) 拼接路径
(4) 写入本地
(5) 从本地读取数据

下面 来说一下怎么将复杂对象存储到本地 所谓复杂对象就是指 在实际应用中 我们用到的model数据 将复杂数据存储到本地要用到归档 将复杂数据从本地中读出来要用到反归档
1 我们创建一个自定义的类(继承与 NSObject)

#import <Foundation/Foundation.h>
// 1. 将需要归档的类  签订协议 签订   NSCoding协议         

@interface Book : NSObject   <NSCoding>

@property (nonatomic, copy)   NSString *bookName;
@property (nonatomic, copy) NSString *bookPrice;
@property (nonatomic, copy) NSString *writer;
@property (nonatomic, copy) NSString *bookAddress;
@property (nonatomic, copy) NSString *bookType;

@end


#import "Book.h"

@implementation Book
// 2. 签订协议后 必须实现 下面两个方法
// 初始化是 读取数据的
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
    _bookName = [aDecoder decodeObjectForKey:@"bookName"];
    _bookPrice = [aDecoder decodeObjectForKey:@"bookPrice"];
    _writer = [aDecoder decodeObjectForKey:@"writer"];
    _bookAddress = [aDecoder decodeObjectForKey:@"bookAddress"];
    _bookType = [aDecoder decodeObjectForKey:@"bookType"];
}
return self;
}
// 写入数据的方法 赋值
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:_bookName forKey:@"bookName"];
[aCoder encodeObject:_bookPrice forKey:@"bookPrice"];
[aCoder encodeObject:_writer forKey:@"writer"];
[aCoder encodeObject:_bookAddress forKey:@"bookAddress"];
[aCoder encodeObject:_bookType forKey:@"bookType"];
}



@end


Book *book = [Book new];
book.bookName = @"傲慢与偏见";
book.bookPrice = @"18.5";
book.writer = @"josejjs";
book.bookType = @"story";
book.bookAddress = @"English";

NSString *bookPath = [[pathArray firstObject] stringByAppendingPathComponent:@"book.plist"];
BOOL isBook = [NSKeyedArchiver archiveRootObject:book toFile:bookPath];
if (isBook) {
    NSLog(@"写入成功");
} else {
    NSLog(@"写入失败");
}

// 2. 反归档(取出对象 反归档走的是初始化)
Book *book1 = [NSKeyedUnarchiver unarchiveObjectWithFile:bookPath];
NSLog(@"%@", book1.bookName);

Copyright © 2019- how234.cn 版权所有 赣ICP备2023008801号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务