iPhone持久存储

Neo*_*Neo 1 iphone cocoa cocoa-touch objective-c

我需要在我的应用程序执行时存储某些信息,并在应用程序启动时再次获取它.我尝试使用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];
Run Code Online (Sandbox Code Playgroud)

阅读

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;
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*ton 10

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

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

此外,您不必担心文件句柄.NSData能够将自己写入磁盘:

BOOL result = [data writeToFile:savePath atomically:YES];
Run Code Online (Sandbox Code Playgroud)