您的位置:首页 > 其它

数据持久化初级沙盒

2015-12-16 20:12 281 查看
#import <Foundation/Foundation.h>

@interface Phone : NSObject<NSCoding>

@property(strong,nonatomic) NSString *color;

@property(strong,nonatomic) NSString *brand;

@property(strong,nonatomic) NSString *price;

@end

#import "Phone.h"

@implementation Phone

//复杂对象想要实现数据持久化(写入文件),必须遵循NSCoding协议,实现以下两个方法

//编码

//在这个方法中,我们需要事先没一个需要归档的属性,并标记Key值

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

[aCoder encodeObject:_color forKey:@"color"];

[aCoder encodeObject:_brand forKey:@"brand"];

[aCoder encodeObject:_price forKey:@"price"];

}

//解码

//在这个方法中,我们需要完成属性的反归档操作,根据编码时的key值一一对应获取相应的值

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

if(self =[super init]) {

_color = [aDecoder decodeObjectForKey:@"color"];

_brand = [aDecoder decodeObjectForKey:@"brand"];

_price = [aDecoder decodeObjectForKey:@"price"];

}

return self;

}

@end

#import "ViewController.h"

#import "Phone.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

//沙盒文件目录

/*

// //沙盒主路径

// //每个应用程序运行的时候都会生成一个专属的沙盒路径,应用程序在使用期间的非代码文件都会储存在当前的沙河目录中

// NSString *homePath = NSHomeDirectory();

// NSLog(@"%@",homePath);

//

// //Documents//用来存储永久性数据的文件夹,程序运行时需要的必要资源 (例如数据库),全部存放在这里,iTunes会自动备份此文件夹的内容

// //第一个参数:要查询的路径

// //第二个参数:要查询路径所属的用户(iOS下通常为单用户)

// //第三个参数:是否显示绝对路径

// //区别于Mac OS(OS X)的开发,iOS开发中通常一个应用程序只有一个文件路径

// //由于OC同时支持苹果系列的操作系统的开发,所以在Mac OS下会生成很多个路径,而在iOS下,通常会生成一个路径,所以储存路径是数组

// //iOS端的路径 只要取出数组中唯一一个元素就可以

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

//

// NSLog(@"%@",documentsPath);

//

// //Library:保存应用程序运行期间生成的内容

// NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];

// NSLog(@"%@",libraryPath);

//

// //Caches:主要用来保存应用程序的缓存文件//不会被备份

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

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

//

// //Preferences:主要用来保存应用程序的偏好设置//会被备份

// NSString *preferencesPath = [libraryPath stringByAppendingString:@"/Preferneces"];

//

// NSLog(@"%@",preferencesPath);

// //单例:用来存储程序的偏好设置,会写入Preferences文件夹,锁一般情况下,我们不直接去打开或者操作Preferences文件夹,而是通过NSUserDefaults创建的对象来完成偏好设置的内容,并且写到本地

// //巧用:NSUserDefaults可以用来传值(单例)

// NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];

// //夜间模式

// [userDefault setBool:YES forKey:@"NightMode"];

// NSLog(@"%d",[userDefault boolForKey:@"NightMode"]);

//

//

// //tmp :临时文件夹,应用程序在运行期间产生的临时碎片都会存储在这里,通常在文件下载完成或者是应用程序退出的时候清空此文件夹,iTunes不会备份此文件

// //小tips;因为系统会清空,所以下载或者其他临时文件如果想要持久使用就要及时转移走;

// NSString *tmpPath = NSTemporaryDirectory();

//

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

*/

//简单对象写入文件

/* //字符串写入文件

NSString *incantation = @"I love my iOS teacher";

//设置路径

NSString *path = NSHomeDirectory();

path = [path stringByAppendingString:@"/咒语"];

//写入文件

//第一个参数:路径

//第二个参数:是否进行线性操作(YES的时候,可以保证发生意外的时候有中转文件储存诗句,纸质完成写入,但是损耗较高,NO的时候,写入速度很快,但是没有安全保障)

//第三个参数:编码方式

//第四个参数:错误对象

[incantation writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];

//读取文件

//第一个参数:路径

//第二个参数:编码方式 (切记要和写入的时候一致)

//第三个参数:错误对象

NSString *resyleString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

*/

//数组写入文件

/*

NSArray *array =@[@"Selina",@"KarTing",@"Pig",@"HellRun",@"Alice",@"TanGa"];

//准备文件路径

NSString *path = NSHomeDirectory();

path =[path stringByAppendingPathComponent:@"Girls.txt"];

//写入文件

[array writeToFile:path atomically:YES];

//读取文件

NSArray *resultArray = [NSArray arrayWithContentsOfFile:path];

NSLog(@"%@",resultArray);

*/

//字典写入文件

/*

NSDictionary *dictionary = @{@"name":@"licong",@"age":@"21"};

//准备文件路径

NSString *path= NSHomeDirectory();

path = [path stringByAppendingPathComponent:@"dictionary.txt"];

//写入文件

[dictionary writeToFile:path atomically:YES];

//读入文件

NSDictionary *resultDic = [NSDictionary dictionaryWithContentsOfFile:path];

NSLog(@"%@",resultDic);

*/

//图片写入文件

/*

UIImage *image =[UIImage imageNamed:@"fallinlove.jpg"];

//准备文件路径

NSString *path = NSHomeDirectory();

path = [path stringByAppendingString:@"/love.jpg"];

// 写入文件

//第二个参数:缩放倍数

NSData *data = UIImageJPEGRepresentation(image, 1);

[data writeToFile:path atomically:YES];

//读入文件

UIImageView *imgView =[[UIImageView alloc] initWithFrame:self.view.bounds];

imgView.image = [UIImage imageWithContentsOfFile:path];

[self.view addSubview:imgView];

*/

//复杂对象的写入文件

/*

Phone *phone =[Phone new];

phone.color = @"GreatGlod";

phone.brand = @"HuaWei";

phone.price = @"1999";

//创建Data 对象

NSMutableData *mutableData =[[NSMutableData alloc] initWithCapacity:3];

//创建归档对象

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

//归档

[archiver encodeObject:phone forKey:@"p8"];

//完成归档

[archiver finishEncoding];

//写入文件

NSString *path = NSHomeDirectory();

path = [path stringByAppendingPathComponent:@"phone"];

//

[mutableData writeToFile:path atomically:YES];

//反归档

//创建Data对象

NSData *data = [NSData dataWithContentsOfFile:path];

//创建反归档对象

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

//反归档

Phone *resultPhone = [unarchiver decodeObjectForKey:@"p8"];

//完成反归档

NSLog(@"%@,%@,%@",resultPhone.color,resultPhone.brand,resultPhone.price);

//归档不是数据持久化的方式,而是辅助完成将复杂对象转化为NSData对象的方式,真正完成数据持久化的方式任然是write to fire (写入文件)

//数据持久化方式

//1.属性列表 (plist)

//2.偏好设置 (NSUserDefaults)

//3.写入文件 (write to file)

//4.数据库 (sqlite)

//5.Core Data

//OC里面没有真正意义上的深拷贝,除了归档和反归档

NSLog(@"%@ -- %@",phone,resultPhone);

*/

//文件管理器

NSURLSessionDownloadTask *downloadTask = [[NSURLSession sharedSession] downloadTaskWithURL:[NSURL URLWithString:@"http://d.hiphotos.baidu.com/image/pic/item/241f95cad1c8a786523664e86309c93d70cf5033.jpg"] completionHandler:^(NSURL * _Nullable location, NSURLResponse
* _Nullable response, NSError * _Nullable error) {

// UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];

//

// dispatch_async(dispatch_get_main_queue(), ^{

//

// UIImageView *imgView = [[UIImageView alloc] initWithFrame:self.view.bounds];

// imgView.image = image;

// [self.view addSubview:imgView];

// });

//获取Data对象

NSData *data = [NSData dataWithContentsOfURL:location];

//创建文件管理器

NSFileManager *fileManager = [NSFileManager defaultManager];

//创建一个文件夹

NSString *path = NSHomeDirectory();

path = [path stringByAppendingString:@"/班级私房照"];

//创建文件夹(用过一次就要注释)

// [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];

//创建文件

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

[fileManager createFileAtPath:filePath contents:data attributes:nil];

}];

[downloadTask resume];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: