无法在iPad上将NSString写入文件 [英] Failure to write NSString to file on iPad

查看:171
本文介绍了无法在iPad上将NSString写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用文本文件来保存用户在列表中所做的更改(我这样做的原因是我可以稍后将文本文件上传到PC,并从那里插入它到Excel电子表格中)。我有3个数据结构:一个NSMutableArray键和一个NSMutableDictionary,它的键值是NSStrings的MSMutableArrays。

I'm using a text file to save the changes made by a user on a list (the reason that I'm doing this is so that I can upload the text file to a PC later on, and from there insert it into an Excel spreadsheet). I have 3 data structures: A NSMutableArray of keys, and a NSMutableDictionary who's key values are MSMutableArrays of NSStrings.

我遍历这些数据结构并编译一个看起来很像的文件字符串非常喜欢这样:

I iterate through these data structures and compile a file string that looks much like this:

(Key);(value)\t(value)\t(value):\n(Key);(value).. .so on.

在实际问题上:当我尝试保存它时,它会失败。我99%肯定这是因为我正在使用的文件路径,但我想备份来检查这一点。代码如下:

SO, onto the actual question: When I attempt to save it, it fails. I'm 99% sure this is because of the file path that I'm using, but I wanted backup to check this out. Code follows:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *filePath = [paths objectAtIndex:0];
NSString *fileString = [NSString stringWithString:[self toFileString]];
if(![fileString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL]){
    NSLog(@"File save failed");
} else {
    // do stuff
}

(上面的代码被重新复制,因为实际代码在不同的计算机上。它编译,所以忽略拼写错误?)

(Code above is re-copied, since the actual code is on a different computer. It compiles, so ignore spelling errors?)

我尝试使用NSError,但是我陷入了困境在文档中,我想在尝试弄清楚如何正确使用NSError时可能会问这个问题(可能有点像白痴,对不起)。

I tried using NSError, but I got bogged down in documentation and figured I might as well ask SO while trying to figure out how to properly use NSError (might be a little bit of an idiot, sorry).

99确定它是NSArray *路径线的绊倒,但我不知道如何获取文件目录。

99% sure it's the NSArray *paths line that's tripping it up, but I don't know how else to get the documents directory.

编辑:问题解决了,最后一个问题:如果我将其保存到App的文档目录中,我可以在关闭应用程序后查看它是否正确保存?如果它像我认为的那样工作,是不是在应用程序的模拟器上安装沙箱? (即无法检查)

Problem solved, and one final question: If I save it to the App's document directory, where can I go after I close the app to see if it saved properly? If it works like I think it does, isn't it sandboxed in with the app's installation on the simulator? (i.e. no way of checking it)

推荐答案

NSLog()即filePath字符串。我想你是想写一个目录本身,而不是写一个文件。

NSLog() that filePath string. I think you're trying to write to the directory itself, not to a file.

试试这个:

filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent:@"myfile.txt"];

这篇关于无法在iPad上将NSString写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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