您的当前位置:首页iOS_数据存储

iOS_数据存储

2024-12-13 来源:哗拓教育

PList(XML属性列表)

属性列表是一种 XML 格式的文件,扩展名为 plist 。

  • 如果对象时 NSArray、NSDictionnary 类型,可以使用 writeToFile:atomically: 方法直接写入到属性列表文件;
  • 如果对象时 NSString、NSData 类型,可以使用 writeToFile:atomically:方法写入对应的文件。
  • atomically(写入原子性) YES:先创建一个临时文件,直到内容完成后再倒入目标文件;NO:直接写入文件。

主要操作是在沙盒目录下的几个文件夹下操作

// 文档目录
NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = documents[0];

// 临时目录
NSString *tmpDir = NSTemporaryDirectory();

// 缓存目录
NSArray *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDir = caches[0];

// 保存NSArray
NSString *arrayPath = [docDir stringByAppendingPathComponent:@"array.plist"];
NSArray *arrays = @[@"zhangsan", @"lisi"];
[arrays writeToFile:arrayPath atomically:YES];

//读取 NSArray
NSArray *dataArray = [NSMutableArray arrayWithContentsOfFile:arrayPath];//注意,如果想添加新的数据,需要NSMutable类型的

NSLog(@"array = %@", dataArray);//直接打印数据。
// 保存 Dict
NSString *dictPath = [docDir stringByAppendingPathComponent:@"dict.plist"];
NSDictionary *dict = @{@"name":@"zhangsan", @"name2":@"lisi"};
[dict writeToFile:dictPath atomically:YES];

//获取此路径下的我们需要的数据(NSArray,NSDictionary,NSString...)
NSMutableDictionary *data = [NSMutableDictionary dictionaryWithContentsOfFile:dictPath];//注意,如果想添加新的数据,需要NSMutable类型的
NSLog(@"dict = %@", data);//直接打印数据。
log.png

// doc 下面创建文件夹

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *testDirectory = [docDir stringByAppendingPathComponent:@"test"];
// 创建目录
[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];

NSKeyedArchiver(归档、反归档)

归档是一种很常用的文件储存方法,几乎任何类型的对象都能够被归档储存(实际上是一种文件保存的形式).
特点如下:
1.支持复杂的数据对象;
2.对自定义对象进行归档处理,对象中的属性需要基本数据类型,或者是实现了NSCoding协议的对象类型;
3.自定义对象的类也需要实现NSCoding.
4.NSString、NSDictionary、NSArray、NSData、NSNumber等对象可以直接使用 NSKeyArchiver归档

归档字符串

NSString *homeDictionary = NSHomeDirectory();//获取根目录
NSString *homePath  = [homeDictionary stringByAppendingPathComponent:@"test.archiver"];//添加储存的文件名
BOOL flag = [NSKeyedArchiver archiveRootObject:@"guidang" toFile:homePath];//归档一个字符串或数组
NSString *string = [NSKeyedUnarchiver unarchiveObjectWithFile:homePath];
NSLog(@"归档 = %@",string);

归档多对象

//准备数据  
CGPoint point = CGPointMake(1.0, 2.0);  
NSString *info = @"坐标原点";  
NSInteger value = 10;  
NSString *multiHomePath = [NSHomeDirectory() stringByAppendingPathComponent:@"multi.archiver"];  
NSMutableData *data = [[NSMutableData alloc]init];  
NSKeyedArchiver *archvier = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];  

//对多个对象进行归档  
[archvier encodeCGPoint:point forKey:@"kPoint"];  
[archvier encodeObject:info forKey:@"kInfo"];  
[archvier encodeInteger:value forKey:@"kValue"];  
[archvier finishEncoding];  
[data writeToFile:multiHomePath atomically:YES];  

NSMutableData *dataR = [[NSMutableData alloc]initWithContentsOfFile:multiHomePath];  
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:dateR];  
CGPoint pointR = [unarchiver decodeCGPointForKey:@"kPoint"];  
NSString *infoR = [unarchiver decodeObjectForKey:@"kInfo"];  
NSInteger valueR = [unarchiver decodeIntegerForKey:@"kValue"];  
[unarchiver finishDecoding];  
NSLog(@"%f,%f,%@,%d",pointR.x,pointR.y,infoR,valueR); 

归档自定义对象

Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject <NSCoding>
@property (strong, nonatomic) NSString *name;
@property (assign, nonatomic) int age;
+ (id) initPersonWithName: (NSString *) name age: (int) age;
@end

Person.m

@implementation Person
+ (id) initPersonWithName:(NSString *)name age:(int)age
{
    Person *person = [[Person alloc]init];
    person.name = name;
    person.age = age;
    return person;
}

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

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

@end

归档、反归档

Person *person = [Person initPersonWithName:@"zhangsan" age:18];
BOOL flag1 = [NSKeyedArchiver archiveRootObject:person toFile:homePath];
Person *unPerson = [NSKeyedUnarchiver unarchiveObjectWithFile:homePath];
NSLog(@"%@= %d", unPerson.name, unPerson.age);

Preference(偏好设置)

NSUserDefaults快速读写,利用系统提供的方法,我们可以快速保存简单数据类型,如用户登录用户名密码。NSUserDefaults支持的数据类型有:NSNumber(NSInteger、float、double),NSString,NSDate,NSArray,NSDictionary,BOOL.

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];//获取标准函数对象  
NSMutableDictionary *defaultcoordinate = [defaults objectForKey:@"default_coordinate"];//通过对象获取名称下NSMutableDictionary数据  
NSString *currentCity = [defaultcoordinate objectForKey:@"c_name"]; 
[defaults setObject:@"kaka" forKey:@"newdata"];//添加id对象类型数据  
[defaults objectForKey:@"newdata"];//获取对象类型数据  

[defaults setDouble:2013 forKey:@"double"];//添加double类型数据  
[defaults doubleForKey:@"double"];//获取double类型数据  

[defaults setBool:NO forKey:@"BOOL"];//添加BOOL类型数据  
[defaults boolForKey:@"BOOL"];//获取BOOL类型数据  

[defaults setInteger:12 forKey:@"int"];//添加int类型数据  
[defaults integerForKey:@"int"];//获取int类型数据  

[defaults setFloat:0.23 forKey:@"float"];//添加Float类型数据  
[defaults floatForKey:@"float"];//获取float类型数据  

[defaults removeObjectForKey:@"newdata"];//删除对象数据 

[defaults synchronize];//Synchronize同步操作
显示全文