Search code examples
cocoafile-ionsdateformatternsdata

How to preserve colon character in filename when using NSData method "writeToFile:atomically:"?


When I run the following code, the filename that gets written on the disk ends up like this: "MyFileName_2011-02-07_13/07/55.png". I'd like to keep the colon character, not forward slashes. When I NSLog "fileName" in console it looks right. What am I missing?

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd_HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];

NSString *fileName = [NSString stringWithFormat:@"MyFileName_%@.png", dateString];

[myNSData writeToFile:fileName atomically:NO];

Solution

  • The filename does contain the colon; the Finder replaces it with slashes.

    This is a holdover from when you couldn't use a colon because it was the path separator on Mac OS. Now, the path separator is the slash, hence the switch.

    The Finder still won't let you enter a colon; if you try to enter a slash, it'll succeed, but save the name with a colon in its place.

    Pretty much everywhere else, including in Cocoa, a colon is valid (not a path separator) but a slash isn't.