简体   繁体   中英

Using NSFileHandle Properly

So I ran into a very weird issue this morning. I have an NSMutableString that constantly grows as time goes on, and it occasionally saves itself to the disk, basically creating a constantly growing text file. It was working perfectly, until a few hours ago. I changed none of the code in the method either by the way. This is the code I'm using, the NSMutableString is called stringToSave:

- (void)saveToTextFile {
    NSLog(@"SaveTextToFile called");

    // Get Current date and time:
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];

    NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
    [timeFormat setDateFormat:@"hh:mm"];

    NSDate *now = [[NSDate alloc] init];

    NSString *theDate = [dateFormat stringFromDate:now];
    NSString *theTime = [timeFormat stringFromDate:now];

    NSString *dateToBeDisplayed = [NSString stringWithFormat:@"Date: %@, Time: %@.", theDate, theTime];


    // Create text to save, and save it.
    stringToSave = [NSString stringWithFormat:@"\n %@ ",dateToBeDisplayed];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"mynotes"];

    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
    [fileHandle seekToEndOfFile];
    [fileHandle writeData:[stringToSave dataUsingEncoding:NSUTF8StringEncoding]];
    [fileHandle closeFile];


    // Check what's saved there.
    NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSStringEncodingConversionAllowLossy error:nil];

    NSLog(@"File Content: %@", content);
    NSLog(@"stringtosave: %@", stringToSave);
}

The odd part is, stringToSave always has the proper data in it in the NSLog, while content remains empty. Does anyone see anything wrong with how I'm saving my data above?

Does the file exist when you start? https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsfilehandle_Class/Reference/Reference.html says that if the file does not exist, then your fileHandleForWritingAtPath: returns nil.

The file would not exist if you delete and reinstall your app (either on the device on the the simulator).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM