使用writeToFile保存NSString只会保存到一个位置

时间:2013-03-10 05:34:52

标签: objective-c nsstring writetofile

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

1 个答案:

答案 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] );
}