Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
like image 561
anna Avatar asked Dec 17 '22 17:12

anna


2 Answers

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.

like image 150
Peter Hosey Avatar answered Jan 04 '23 00:01

Peter Hosey


It is generally not possible to have the : character in filenames on Darwin (i.e. OS X and iOS). Just try to rename a file on your Mac to contain the :. The writeToFile: method apparently simply replaces illegal characters instead of producing and error.

like image 42
mrueg Avatar answered Jan 04 '23 01:01

mrueg