iPhone持久存储 [英] iPhone Persistent Storage

查看:80
本文介绍了iPhone持久存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在执行应用程序时存储某些信息,并在应用程序启动时再次提取它。我试图使用GData存储在XML中,但没有成功。
我使用NSFileHandle它不给我一个错误,但它无法创建一个.txt文件读/写的目的。有没有任何其他方式在iPhone上存储和检索数据。下面是NSFileHandle的代码。

I need to store certain information while my application is executing and again fetch it at the time the application starts. I tried storing it in XML using GData but didn't succeed. I used the NSFileHandle it doesn't give me an error but it fails to create a .txt file for read / write purpose. Is there any other way of storing and retrieving the data on the iPhone. Below is my code for NSFileHandle.

NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"myFile.txt"];
//NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:@"file://localhost/Users/shraddha/Desktop/info.txt"];
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:@"myFile.txt"];
[fh seekToEndOfFile];
NSData *data = [camName dataUsingEncoding:NSASCIIStringEncoding];
[fh writeData:data];
[fh closeFile];

阅读

NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"myFile.txt"];
//NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:@"file://localhost/Users/shraddha/Desktop/info.txt"];
NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:@"myFile.txt"];
if(fh == nil)
    return nil;
else
{
    NSData *data = [fh readDataOfLength:8];
    NSString *retStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    return retStr;
}


推荐答案

到您可能没有权限的资源目录。尝试将代码的第一行改为指向文档目录:

You're trying to write to the resource directory which you probably don't have permission to do. Try changing the first line of your code to point to the document directory:

NSArray *savePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSMutableString *savePath = [NSMutableString stringWithString:[savePaths objectAtIndex:0]];
[savePath appendString:@"/myFile.txt"];

此外,您不需要担心文件句柄。 NSData 能够写入磁盘:

Also, you don't need to worry about file handles. NSData is capable of writing itself to disk:

BOOL result = [data writeToFile:savePath atomically:YES];

这篇关于iPhone持久存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆