1

使用下面的代码是我可以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;
4

1 回答 1

2

如果您实际上在 " " 方法中使用错误参数,您最终可能会找到解决方案writeToFile

例如:

NSError * error = NULL;
BOOL success = [content writeToFile:fileName atomically:NO encoding:NSUTF8StringEncoding error:&error];
if(success == NO)
{
    NSLog( @"error saving to %@ - %@", fileName, [error localizedDescription] );
}
于 2013-03-10T05:37:48.617 回答