使用下面的代码是我writeToFile
实际保存文件的唯一方法。它输出到这个目录:
/Users/Eric/Library/Containers/net.ericmann.Event-Gadget-Workshop-App/Data/Documents/gadget.ics
- (IBAction)Saved:(id)sender {
[self writeToTextFile];
//mySaved.stringValue = [NSString stringWithFormat:@"Saved!"];
}
-(void) writeToTextFile{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//NSString *pathToDesktop = [NSString stringWithFormat:@"/Users/%@/Desktop", NSUserName()];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/gadget.ics", documentsDirectory];
//create content - four lines of text
NSString *content = myOutput.stringValue;
//save content to the documents directory
[content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
mySaved.stringValue = fileName;
myTestBox.stringValue = fileName;
}
现在,如果我使用下面的代码,那么什么都不会写。我有测试文件名输出,它指向这里:
/Users/Eric/Desktop/gadget.ics
-(void) writeToTextFile{
//get the documents directory:
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
//NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pathToDesktop = [NSString stringWithFormat:@"/Users/%@/Desktop", NSUserName()];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/gadget.ics", pathToDesktop];
//create content - four lines of text
NSString *content = myOutput.stringValue;
//save content to the documents directory
[content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
mySaved.stringValue = fileName;
myTestBox.stringValue = fileName;
答案 0 :(得分:2)
如果您真的在“writeToFile
”方法中使用错误参数,您可能最终会找到解决方案:
e.g:
NSError * error = NULL;
BOOL success = [content writeToFile:fileName atomically:NO encoding:NSUTF8StringEncoding error:&error];
if(success == NO)
{
NSLog( @"error saving to %@ - %@", fileName, [error localizedDescription] );
}