如何将cocoa/xcode中的文本/数据保存到文件中?
问题描述:
对于显而易见的问题,我很抱歉,但在写数据到文件时应该注意些什么,因为我的程序可以在程序运行时读取它刚刚写入的数据,但是当我停止它时,这些文件已空如何将cocoa/xcode中的文本/数据保存到文件中?
使用NSFileHandle,为了与后来写入数据,并关闭文件试过了,没有帮助......目前,我使用:
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:newArray];
[encodedObject writeToFile:string atomically:YES];
,无不管我做什么,我无法得到最简单的NSString永久保留在文件中
我该怎么办?
感谢@LetzFlow,但它还没有解决它。现在
,我使用:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
string = [NSString stringWithFormat:@"%d.rtf",fileName];
NSString *file = [documentsDirectory stringByAppendingPathComponent:string];
//NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:file];
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:newArray];
[encodedObject writeToFile:file atomically:YES];
//[fileHandle writeData:encodedObject];
//[fileHandle closeFile];
NSLog(@"%@",[NSString stringWithContentsOfFile:file encoding:NSStringEncodingConversionAllowLossy error:nil]);
序列化对象的数组,并且所述的NSLog显示有效阵列。但是,当我稍后查看文件时,或者尝试反序列化阵列(如下所示)时:(
NSString *stringX = [NSString stringWithFormat:@"%d.rtf",fileName];
NSData *encodedObjectX = [NSData dataWithContentsOfFile:stringX];
NSArray *newArrayX = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObjectX];
TurnigButton *button = [[newArrayX objectAtIndex:1] objectAtIndex:5];
NSLog(@"%d", button.idNum);
它只是打印(空)。 (当他们在一次执行中一个接一个地执行时,它反序列化就好)
我很感激帮助。
答
问题是你在哪里写你的文件?因为您不允许在iOS系统中编写文件。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
文档目录通常是一个地方,你可以写文件,所以你可能想试试。
试试这个:1.从模拟器运行,2.停止,3.检查MAC地址上保存的文件是否存在。 – user523234 2012-07-07 19:18:26
尝试过,不起作用...文件保持空白。 – user1508829 2012-07-08 14:34:45