IOS中常用的几种数据存储

iOS数据存储方式详解
本文详细介绍了iOS开发中常见的三种数据存储方式:plist文件存储、偏好设置存储以及自定义对象归档存储。通过具体的代码实例展示了如何实现数据的保存与读取。

1,pilist

- (IBAction)save:(id)sender {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    
    path = [path stringByAppendingPathComponent:@"data.plist"];
    NSLog(@"%@",path);
    NSArray *data = @[@1,@2,@3];
    
    [data writeToFile:path atomically:YES];
    
}
- (IBAction)read:(id)sender {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    
    path = [path stringByAppendingPathComponent:@"data.plist"];
    
    NSArray *array = [NSArray arrayWithContentsOfFile:path];
    NSLog(@"%@",array);
    
}

2,偏好设置

- (IBAction)save:(id)sender {
    // [NSUserDefaults standardUserDefaults]可以直接操作偏好设置文件夹
    NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
    
    // 自动帮我们生成一个plist文件存放在偏好设置的文件夹
    [de setObject:@"cg" forKey:@"name"];
    
    // 同步:把内存中的数据和沙盒同步
    [de synchronize];
    
}
- (IBAction)read:(id)sender {
    NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
    
    NSString *name = [de objectForKey:@"name"];
    
    NSLog(@"%@",name);
    
    
}

3,自定义对象存储

person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject<NSCoding>

@property (nonatomic,copy) NSString *name;
@property (nonatomic,assign) NSInteger age;

@end

person.m

#import "Person.h"

@implementation Person


- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeInteger:_age forKey:@"age"];
    [aCoder encodeObject:_name forKey:@"name"];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {
        _age = [aDecoder decodeIntegerForKey:@"age"];
        _name = [aDecoder decodeObjectForKey:@"name"];
    }
    return self;
}
@end

控制器:

- (IBAction)save:(id)sender {
    Person *p = [[Person alloc] init];
    
    
    p.age = 10;
    p.name = @"cg";
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    
    NSString *filePath = [path stringByAppendingPathComponent:@"person.data"];
    
    [NSKeyedArchiver archiveRootObject:p toFile:filePath];
    
    
    
}
- (IBAction)read:(id)sender {
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    
    NSString *filePath = [path stringByAppendingPathComponent:@"person.data"];
    
    Person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    NSLog(@"%ld---%@",(long)p.age,p.name);
}


转载于:https://my.oschina.net/cgphp/blog/413480

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值