iOS开发之数据读写

iOS进阶

1:数据处理之数据读写

 

1):获取当前应用程序的沙盒根目录

 

 NSString *rootPath = NSHomeDirectory();

 NSLog(@"%@",rootPath);

rootPath就是根目录

然后将打印出来的文件目录右键单击选择services下的Reveal In Finder

 

2):

Documents:存储持久化文件数据

Library/Caches:存储缓存数据

Library/Preferences:存储应用的所有偏好设置

tmp:保存应用运行时所需的临时数据

 

3):定位当前应用程序的沙盒根目录

 

 //1.Documents

 NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

    NSLog(@"%@",docPath);

    

    

    //2.library

    NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];

    NSLog(@"libPath is %@",libPath);

    

    

    //3.library/Caches

    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];

    NSLog(@"cachesPath is %@",cachesPath);

    

    //4.library/preferences   只能用拼接方法定位

    NSString *prePath = [libPath stringByAppendingPathComponent:@"Preferences"];

    NSLog(@"prePath is %@",prePath);

    

    //5.tmp

    NSString *tmpPath = NSTemporaryDirectory();

    NSLog(@"tmpPath is %@",tmpPath);

 

4):存储应用程序的偏好设置的类:NSUserDefaults

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults] ;

[defaults setObject:@"tang" forKey:@"name"] ;

//同步

[defaults synchronize] ;

    NSLog(@"%@",[defaults objectForKey:@"name"]);

 

5):简单对象的读写操作

只有四种简单的数据类型才能直接写入进文件

NSString NSDictionary NSData NSArray

第一步:获取沙盒下文件夹Documents的路径

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

第二步:创建需要写入的文件路径

    NSString *filePath = [docPath stringByAppendingString:@"/text.txt"];

第三步:创建字符串对象

    NSString *string = @"is副科级领导盖房了";

第四步:写入,四种简单的数据类型的写入方法差不多的

    [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

第五步:读取字符串对象

    NSString *resultStr = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

数组和字典可参照字符串对象的写入读取方法

*NSData对象的写入和读取(将图片存储)

第一步和第二步是一样的

第三步:    UIImage *image = [UIImage imageNamed:@"0"];

第四步:    NSData *data = UIImagePNGRepresentation(image);

第五步:写入

    [data writeToFile:dataPath atomically:YES];

 

读取图片并在模拟器上显示:

NSData *resultData = [NSData dataWithContentsOfFile:dataPath];

    UIImage *reImage = [UIImage imageWithData:resultData];

    UIImageView *imageView = [[UIImageView alloc] initWithImage:reImage];

    imageView.frame = self.view.bounds;

    [self.view addSubview:imageView];

 

6):在沙盒目录下创建文件

第一步:找到沙盒路径(caches)

 //1.获取Documents目录

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

    //2.创建文件路径

    NSString *filePath = [docPath stringByAppendingString:@"/baobao.txt"];

    //3.创建文件管理对象

    NSFileManager *manager = [NSFileManager defaultManager];

    //4.创建

    [manager createFileAtPath:filePath contents:[@"sdfasdfs" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];

    NSLog(@"%@",filePath);

//计算文件或文件夹的大小

    NSDictionary *dic = [manager attributesOfItemAtPath:filePath error:nil];

    NSLog(@"%@",dic);

    NSNumber *number = [dic objectForKey:NSFileSize];

    NSLog(@"%@",number);

7):创建文件夹和创建文件的核心代码差别在:

a:文件夹路径没有后缀名,文件有

b:文件管理器创建方法的不同

 

//2.创建文件夹的路径

    NSString *filePath = [cachesPath stringByAppendingString:@"/text"];

    

    //3.创建文件管理器对象

    NSFileManager *manager = [NSFileManager defaultManager];

    [manager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];

 

/*

 Documents文件夹下,创建一个文件夹(path),在该文件夹下创建一个文件(test.txt),将一个图片对象存入到该文件中,然后在Caches文件夹下创建一个文件夹名为"testDirectroy",test.txt文件复制到这个文件夹下.

 */

 - (void)moveFile {

 

    //1.获取Documents目录

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

    //2.创建文件夹路径

    NSString *filePath = [docPath stringByAppendingString:@"/path"];

    NSFileManager *manager = [NSFileManager defaultManager];

    

    [manager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];

    //3.创建文件路径

    NSString *testPath = [filePath stringByAppendingString:@"/test.txt"];

    

    [manager createFileAtPath:testPath contents:[@"aa" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];

    //4.写入图片

    UIImage *image = [UIImage imageNamed:@"0"];

    NSData *data = UIImagePNGRepresentation(image);

    [data writeToFile:testPath atomically:YES];

    

    //5.caches目录

    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

    //6.创建文件夹testDirectroy

    NSString *directoryPath = [cachesPath stringByAppendingPathComponent:@"testDirectroy"];

    [manager createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil];

    

    //7创建一个和documents中需要复制的文件同名的文件

    NSString *desPath = [directoryPath stringByAppendingString:@"/test.txt"];

    

    //8.复制时需要创建文件管理器

    [manager copyItemAtPath:testPath toPath:desPath error:nil];

    NSLog(@"%@",directoryPath);

    

 

}

 

/*

练习要求:

 Documents目录下创建一个文件text.txt

 从文件的偏移量为3的时候开始追加内容1234

 */

- (void)addContent {

    //1.得到Documents目录

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

    //2.创建文件夹路径

    NSString *filePath = [docPath stringByAppendingPathComponent:@"fiel"];

    NSFileManager *manager = [NSFileManager defaultManager];

    [manager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];

    //3.创建文件路径

    NSString *textPath = [filePath stringByAppendingPathComponent:@"/text.txt"];

    [manager createFileAtPath:textPath contents:[@"hahahahahaha" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];

    //4.创建文件对接器

    NSFileHandle *handle = [NSFileHandle fileHandleForUpdatingAtPath:textPath];

    //此时文件在更新状态下,即可读也可写

    [handle seekToFileOffset:3];

    

    //5.开始在偏移量为3的地方写入字符串

    [handle writeData:[@"1234" dataUsingEncoding:NSUTF8StringEncoding]];

    [handle closeFile];

    NSLog(@"%@",textPath);

 

}

 

//核心代码如下

//创建文件对接对象

    NSFileHandle *handle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];

    //此时的文件对接对象 既可以读 也可以写

    

    

    //将偏移量移动到3的位置

    [handle seekToFileOffset:3];

    

    //写入数据

    [handle writeData:[@"1" dataUsingEncoding:NSUTF8StringEncoding]];

    

    //执行完操作之后不要忘了关闭文件

    

    [handle closeFile];

 

 

8):复杂文件的归档和反归档(持久化操作)

//归档

- (void)archiver {

    

    //1.创建person对象

    Person *p1 = [[Person alloc] initWithName:@"tangxi" age:@"18"];

    Person *p2 = [[Person alloc] initWithName:@"aren" age:@"20"];

    //2.获取Documents目录

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

    NSString *filePath = [docPath stringByAppendingString:@"/haha.txt"];

    //3.创建可变数据对象

    NSMutableData *data = [NSMutableData data];

    //4.创建归档类的对象

    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

    //5.person对象归档

    [archiver encodeObject:p1 forKey:@"person1"];

    [archiver encodeObject:p2 forKey:@"person2"];

    

    //6.结束归档

    [archiver finishEncoding];//此时不管有几个对象没有被归档都会停止归档了

    //7.将可变数据data写入创建的文件

    

    [data writeToFile:filePath atomically:YES];

    NSLog(@"%@",filePath);

 

}

 

//反归档

- (void)unarchiver {

    

    //1.获取Documents目录

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

    NSString *filePath = [documents stringByAppendingPathComponent:@"haha.txt"];

    

    NSData *data = [NSData dataWithContentsOfFile:filePath];

    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

   Person *person = [unarchiver decodeObjectForKey:@"person1"];

    NSLog(@"name is %@, age is %@",person.name,person.age);

    [unarchiver finishDecoding];

 

}

//还要创建一个模型对象Person,遵循NSCoding协议

实现两个协议方法:

- (instancetype)initWithName:(NSString *)name age:(NSString *)age {

    self = [super init];

    if (self) {

        self.name = name;

        self.age = age;

    }

    return self;

 

}

 

- (void)encodeWithCoder:(NSCoder *)aCoder {

    

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

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

    

 

}

- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder {

    

    NSString *name = [aDecoder decodeObjectForKey:@"name"];

    NSString *age = [aDecoder decodeObjectForKey:@"age"];

    return [self initWithName:name age:age];

    

 

}

 

//4.写入图片

    UIImage *image = [UIImage imageNamed:@"0"];

    NSData *data = UIImagePNGRepresentation(image);

    [data writeToFile:testPath atomically:YES];

    

//4.创建文件对接器

    NSFileHandle *handle = [NSFileHandle fileHandleForUpdatingAtPath:textPath];

    //此时文件在更新状态下,即可读也可写

    [handle seekToFileOffset:3];

    

    //5.开始在偏移量为3的地方写入字符串

    [handle writeData:[@"1234" dataUsingEncoding:NSUTF8StringEncoding]];

    [handle closeFile];

    NSLog(@"%@",textPath);

posted @ 2016-03-02 20:02  aRenOuBa  阅读(234)  评论(0编辑  收藏  举报