数据持久存储到IOS文件系统中有三种不同的机制:属性列表,对象归档,嵌入式数据库SQLite3(另外还有其他方法,可以用传统的C
IO函数读取或者写入数据,也可以使用Cocoa的低级文件管理工具)
每一个应用程序支持三个文件夹 Documents, Library 和 tmp。应用程序将其数据存储在Documents中,(但基于NSUserDefaults的首选设置除外,它存储在Library/Preferences文件夹中),当ios设备同步时,不会去备份/tmp中的文件。
1。 下面这句话将返回Documents目录
NSString *Path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
我们可以通过在这个路径结尾附加一个字符串来创建一个文件名,用于执行读取或者写入操作。
NSString *filename = [Path stringByAppendingPathComponent:@"test.txt"];
上面这句话结束之后会filename将包含test.txt文件的完整路径,该文件位于应用程序的Documents目录下,我们可以用filename来创建读取和写入文件。
2。获取对应应用程序临时目录的引用比较方便,
NSString *tmpPath = NSTemporaryDirectory();
3,下面是基本的代码把一个数组写入文件中,(属性列表)
wiriteToFile
NSString *str = @"abc";
NSString *astr = @"efg";
NSArray *Array = [NSArray arrayWithObjects:str, astr, nil];
//Save
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
NSLog(@"Documents directory not found!");
}
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"Savedatas.plist"];
[[NSArray arrayWithObjects:Array,nil] writeToFile:appFile atomically:NO];
//load
if([[NSFileManager defaultManager] fileExistsAtPath:appFile])
self.SaveDataArray = [NSMutableArray arrayWithContentsOfFile:appFile];
else
self.SaveDataArray = [NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Savedatas" ofType:@"plist"]];
NSArray *strArray = [self.SaveDataArray objectAtIndex:0];
str = [strArray objectAtIndex:0];
astr = [strArray objectAtIndex:1];
4.归档 例子(NSKeyedArchiver)
NSString *str = @"abc";
NSString *astr = @"efg";
NSArray *Array = [NSArray arrayWithObjects:str, astr, nil];
//Save
NSString *Path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *filename = [Path stringByAppendingPathComponent:@"test"];
[NSKeyedArchiver archiveRootObject:Array toFile:filename];
str = @"a";
astr = @"";
//load
NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile: filename];
str = [arr objectAtIndex:0];
astr = [arr objectAtIndex:1];
NSLog(@"str:%@",str);
NSLog(@"astr:%@",astr);
5.例子(NSUserDefaults)
NSString *str = @"abc";
NSString *astr = @"efg";
NSArray *Array = [NSArray arrayWithObjects:str, astr, nil];
//Save
NSUserDefaults *SaveDefaults = [NSUserDefaults standardUserDefaults];
[SaveDefaults setObject:Array forKey:@"SaveKey"];
str = @"a";
astr = @"";
//load
Array = [SaveDefaults objectForKey:@"SaveKey"];
str = [Array objectAtIndex:0];
astr = [Array objectAtIndex:1];
NSLog(@"str:%@",str);
NSLog(@"astr:%@",astr);
6。下面是从论坛中找的两个便利的方法,用于从存储和读取数据。
如下:
-(BOOL) writeApplicationData:(NSDictionary *)data writeFileName:(NSString *)fileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
NSLog(@"Documents directory not found!");
return NO;
}
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
return ([data writeToFile:appFile atomically:YES]);
}
-(id) readApplicationData:(NSString *)fileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSDictionary *myData = [[[NSDictionary alloc] initWithContentsOfFile:appFile] autorelease];
return myData;
}
7.最简单的方法将从网络上下载的图片保存到本地~
//将图片保存到本地
+ (void)SaveImageToLocal:(UIImage*)image Keys:(NSString*)key {
NSUserDefaults* preferences = [NSUserDefaults standardUserDefaults];
//[preferences persistentDomainForName:LocalPath];
[preferences setObject:UIImagePNGRepresentation(image) forKey:key];
}
//本地是否有相关图片
+ (BOOL)LocalHaveImage:(NSString*)key {
NSUserDefaults* preferences = [NSUserDefaults standardUserDefaults];
//[preferences persistentDomainForName:LocalPath];
NSData* imageData = [preferences objectForKey:key];
if (imageData) {
return YES;
}
return NO;
}
//从本地获取图片
+ (UIImage*)GetImageFromLocal:(NSString*)key {
NSUserDefaults* preferences = [NSUserDefaults standardUserDefaults];
//[preferences persistentDomainForName:LocalPath];
NSData* imageData = [preferences objectForKey:key];
UIImage* image;
if (imageData) {
image = [UIImage imageWithData:imageData];
}
else {
NSLog(@"未从本地获得图片");
}
return image;
}
8.这是老外分享的一段代码,保存照片的,很简单,呵呵
参数说明:
NSData to retrieve the image from the URL
NSDocumentDirectory to find Document folder’s Path
UIImagePNGRepresentation to save it as PNG
UIImageJPEGRepresentation to save it as JPEG
代码:
NSLog(@”Downloading…”);
// Get an image from the URL below
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.objectgraph.com/images/og_logo.png"]]];
NSLog(@”%f,%f”,image.size.width,image.size.height);
// Let’s save the file into Document folder.
// You can also change this to your desktop for testing. (e.g. /Users/kiichi/Desktop/)
// NSString *deskTopDir = @”/Users/kiichi/Desktop”;
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// If you go to the folder below, you will find those pictures
NSLog(@”%@”,docDir);
NSLog(@”saving png”);
NSString *pngFilePath = [NSString stringWithFormat:@"%@/test.png",docDir];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
[data1 writeToFile:pngFilePath atomically:YES];
NSLog(@”saving jpeg”);
NSString *jpegFilePath = [NSString stringWithFormat:@"%@/test.jpeg",docDir];
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
[data2 writeToFile:jpegFilePath atomically:YES];
NSLog(@”saving image done”);
[image release];