美文网首页
iOS 简单数据的读写

iOS 简单数据的读写

作者: Joker_King | 来源:发表于2016-05-07 17:32 被阅读134次

简单数据的读写操作

iOS中提供了对一下四种(包括他们的子类)可直接进行文件存取的操作

  • NSString(字符串)
  • NSArray(数组)
  • NSdictionary(字典)
  • NSData(数据)

获取Document文件目录下的文件路径

- (NSString *)GetThefilePath:(NSString *)filePath{
    NSString *Path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:filePath];
    return Path;
}

字符串的存取

存储一个字符串

  • 获取要存储的文件路径
NSString *filePath = [self GetThefilePath:@"name.plist"];
  • 将一个字符串写入到一个文件中
NSString *name = @"蓝欧科技";
[name writeToFile: filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
  • 将一个字符串归档到一个文件中
NSString *name = @"蓝欧科技";
[NSKeyedArchiver archiveRootObject:name toFile:[self GetThefilePath:@"name1.plist"]];

取出一个字符串

  • 简单的读取
NSString *string = [NSString stringWithContentsOfFile:
[self GetThefilePath:@"name.plist"] encoding:NSUTF8StringEncoding error:NULL];
  • 反归档一个字符串
NSString *string = [NSKeyedUnarchiver unarchiveObjectWithFile:[self GetThefilePath:@"name1.plist"]];

数组的存取

存储一个数组

  • 将一个数组写入到文件中
//创建一个数组
NSArray *array = @[@"小李",@"小红",@"Mark"];
[array writeToFile:[self GetThefilePath:@"array.txt"] atomically:YES];
  • 将一个数组归档到一个文件中
NSArray *array = @[@"小李",@"小红",@"Mark"];
[NSKeyedArchiver archiveRootObject:array toFile:[self GetThefilePath:@"array.txt"]];

读取一个数组

  • 简单的读取
NSArray *array_1 = [NSArray arrayWithContentsOfFile:[self GetThefilePath:@"array.txt"]];
  • 反归档一个数组
NSArray *array_2 = [NSKeyedUnarchiver unarchiveObjectWithFile:[self GetThefilePath:@"array.txt"]];

字典的存取

字典的存储

  • 简单的写入
//创建一个字典
NSDictionary *dictionary = @{@"name":@"小红",@"age":@22,@"sex":@"男"};
[dictionary writeToFile:[self GetThefilePath:@"dictionary.txt"] atomically:YES];
  • 将字典归档到文件中
//创建一个字典
NSDictionary *dictionary = @{@"name":@"小红",@"age":@22,@"sex":@"男"};
[NSKeyedArchiver archiveRootObject:dictionary toFile:[self GetThefilePath:@"dictionary.txt"]];

字典的读取

  • 简单的读取
NSDictionary *dictionary_1 = [NSDictionary dictionaryWithContentsOfFile:
[self GetThefilePath:@"dictionary.txt"]];
  • 返归档一个字典
NSDictionary *dictionary_2 = [NSKeyedUnarchiver unarchiveObjectWithFile:
[self GetThefilePath:@"dictionary.txt"]];

NSData的存取

NSData的存储

  • 先将一个图片转换为NSData格式,然后在进行存储
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"4.png"]);
  • 将NSData数据写入到文件中
[imageData writeToFile:[self GetThefilePath:@"image.txt"] atomically:YES];
  • 将NSData数据进行归档
[NSKeyedArchiver archiveRootObject:imageData toFile:[self GetThefilePath:@"image.txt"]];

NSData的读取

  • 从文件读取出来的还是一个NSData类型的数据
NSData *imageData_1 = [NSData dataWithContentsOfFile:[self GetThefilePath:@"image.txt"]];
  • 反归档一个NSData
NSData *imageData_1 = [NSKeyedUnarchiver unarchiveObjectWithFile:[self GetThefilePath:@"image.txt"]];

相关文章

网友评论

      本文标题:iOS 简单数据的读写

      本文链接:https://www.haomeiwen.com/subject/tbxsrttx.html