我正在编写一个文本编辑器应用程序并尝试将 NSString 作为 NSData 存储在文档文件夹中的文件中,例如我希望能够存储一个文件“myText.java”。
我的代码在模拟器上工作。但是,在设备上似乎创建了一个文件,但是当我稍后尝试从文件中加载数据时,我什么也没得到。
我是否必须设置一些项目设置才能启用设备上的文档目录,还是我的代码错误?
这是我的商店代码:
-(void) saveFile:(NSString*)file{
if (![file isEqual:@"Empty"]) {
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullFilePath = [documentsDirectory stringByAppendingPathComponent:file];
[[NSFileManager defaultManager] removeItemAtPath: fullFilePath error: nil];
NSLog(@"File: %@", fullFilePath);
//Above LOGS: /var/mobile/Applications/2310F459-282C-4488-AE24-D5795168F85A/Documents/fg
//save content to the documents directory
NSLog(@"Saving: %@", codeView.text);
// Logs the data i want to store
[[codeView.text dataUsingEncoding:NSASCIIStringEncoding] writeToFile:fullFilePath atomically:YES];
}
}
这是我的加载文件代码:
-(void) loadFile:(NSString*)filename{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *file = [documentsDirectory stringByAppendingPathComponent:filename];
if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
NSLog(@"File found");
//Yes the file is found
theDelegate.fileData = [NSData dataWithContentsOfFile:file];
NSLog(@"Data:%@",[[NSString alloc] initWithData:[NSData dataWithContentsOfFile:file] encoding:NSASCIIStringEncoding]);
// On device and simulator data is found
[theDelegate.codeView setText:[[NSString alloc] initWithData:theDelegate.fileData encoding:NSASCIIStringEncoding]];
//codeView does not get updated with the data.
//NSLog([[NSString alloc] initWithData:theDelegate.fileData encoding:NSASCIIStringEncoding]);
[theDelegate setTitle:filename];
[theDelegate setHasOpenFile:YES];
[theDelegate.codeView setEditable:theDelegate.hasOpenFile];
[theDelegate.codeView setNeedsDisplay];
[self setLanguage:filename];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"File error!" message:@"An error occured when trying to load the selected file." delegate:self cancelButtonTitle:@"OK!" otherButtonTitles:nil, nil];
[alert show];
}
}