iPhone持久存储

时间:2009-04-14 15:17:54

标签: iphone objective-c cocoa cocoa-touch

我需要在我的应用程序执行时存储某些信息,并在应用程序启动时再次获取它。我尝试使用GData将其存储在XML中,但没有成功。 我使用NSFileHandle它没有给我一个错误,但它无法创建一个.txt文件用于读/写目的。有没有其他方法可以在iPhone上存储和检索数据。下面是我的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;
}

3 个答案:

答案 0 :(得分:10)

您正在尝试写入您可能无权执行的资源目录。尝试更改代码的第一行以指向文档目录:

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

此外,您无需担心文件句柄。 NSData能够将自己写入磁盘:

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

答案 1 :(得分:4)

您可以使用sqlite数据库在iPhone上存储持久数据。这篇博文应该让你指出正确的方向:

http://dblog.com.au/iphone-development-tutorials/iphone-sdk-tutorial-reading-data-from-a-sqlite-database/

答案 2 :(得分:3)

每个iPhone应用程序都可以使用它来读取/写入名称/值对,这对于存储用户首选项等小信息非常有用。这些首选项也可以由您的应用程序的用户编辑(如果您选择)。

你有一个比尝试进行文本文件存储和检索更强大的选项(我从来不喜欢这个选项,特别是在iPhone上有蹩脚的XML解析支持)是sqlite。 sqlite是一个非常轻量级的关系数据库引擎,包含在每个iPhone和iPod touch中。

相关问题