我在 ios 5 中遇到文件保存/加载问题?
我有一个应用程序应该保存到文件并稍后加载它。现在,我在 ios 4 上没有遇到任何问题,所以这很令人困惑。我所有的应用程序保存和加载时都发生过这种情况。 代码如下:
- (NSString *)pathOfFile{
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsFolder = [paths objectAtIndex:0];
return [documentsFolder stringByAppendingFormat:@"awesome.plist"];
}
稍后在应用程序中...
[array writeToFile:[self pathOfFile] atomically:YES];
然后当我尝试加载它时...
if ([[NSFileManager defaultManager] fileExistsAtPath:[self pathOfFile]]) {
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filepath];
achi.text = [array objectAtIndex:0];
}
我的应用程序实际上只是跳过 if 语句(这意味着它找不到我认为的文件)。
请帮忙,如果您有不同的保存文件的方法,我很高兴听到它们。
I have an app that is supposed to save to a file and later on load it. Now, I have not had ANY problems what so ever on ios 4, so this is perplexing. This has happened on all my apps saving and loading.
Heres the code:
- (NSString *)pathOfFile{
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsFolder = [paths objectAtIndex:0];
return [documentsFolder stringByAppendingFormat:@"awesome.plist"];
}
Later in in the app...
[array writeToFile:[self pathOfFile] atomically:YES];
And then when I attempt to load it...
if ([[NSFileManager defaultManager] fileExistsAtPath:[self pathOfFile]]) {
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filepath];
achi.text = [array objectAtIndex:0];
}
My app actually just skips over the if statement (Meaning that it can't find the file I think).
Please help, and if you have different methods of saving files, I would be glad to hear to hear them.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的
- (NSString *)pathOfFile
方法是错误的。应该是:Your
- (NSString *)pathOfFile
method is wrong. It should be:在您的
-(NSString *)pathOfFile
方法中,不要使用stringByAppendingFormat:
。使用文件路径时,您应该使用stringByAppendingPathComponent:
,因为它将确保添加适当的斜杠字符(或删除,如果太多):In your
-(NSString *)pathOfFile
method, don't usestringByAppendingFormat:
. When working with file paths, you should instead usestringByAppendingPathComponent:
, as it will ensure that the appropriate slash characters are added (or removed, if there are too many):对我的问题的评论是解决问题的原因,但由于我无法给他正确的答案,所以我将把他的答案粘贴在这里:
你确定目录在那里吗?有时必须创建 Documents 目录。
The comment to my question was what solved the problem, but as I can't give him the correct answer, I'll just write paste his answer here:
Did you make sure the directory is there? Sometimes that Documents directory must be created.