lab*_*b12 5 iphone cocoa objective-c documents ios
我有以下代码:
NSString *fileName = [[NSUserDefaults standardUserDefaults] objectForKey:@"recentDownload"];
NSString *fullPath = [NSBundle pathForResource:fileName ofType:@"txt" inDirectory:[NSHomeDirectory() stringByAppendingString:@"/Documents/"]];
NSError *error = nil;
[textViewerDownload setText:[NSString stringWithContentsOfFile:fullPath encoding: NSUTF8StringEncoding error:&error]];
Run Code Online (Sandbox Code Playgroud)
textviewerdownload是textview显示文件中的文本.实际文件名存储在被NSUserDefault调用的中recentDownload.
当我构建它时,我点击button它所在的,以及我的应用程序crashes.
语法或简单错误有什么问题吗?
在NSBundle类用于您的应用程序包内找到的东西,但文件目录是包外,所以这样你正在生成的路径将无法正常工作.试试这个:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:@"recentDownload.txt"];
Run Code Online (Sandbox Code Playgroud)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *myPathDocs = [documentsDirectory stringByAppendingPathComponent:@"myfile.txt"];
if (![[NSFileManager defaultManager] fileExistsAtPath:myPathDocs])
{
NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:@"myfile" ofType:@"txt"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager copyItemAtPath:myPathInfo toPath:myPathDocs error:NULL];
}
//Load from File
NSString *myString = [[NSString alloc] initWithContentsOfFile:myPathDocs encoding:NSUTF8StringEncoding error:NULL];
Run Code Online (Sandbox Code Playgroud)
这对我有用
无论如何,谢谢大家......
| 归档时间: |
|
| 查看次数: |
21868 次 |
| 最近记录: |