So, here’s my situation :
- I’ve got an application prompting the user to select a folder to save his files
- Now let’s say his files are :
a.png,b.png,c.png
What I want is :
- if file – let’s say –
a.pngalready exists in the selected folder, DON’T overwrite it. Instead create a file with namea (1).png. If a filea (1).pngalready exists, then name it likea (2).png, and so on – pretty much like OS X does when copy-pasting files with the same name.
This is how I’m currently doing it – but it still doesn’t strike me ok :
NSString* target = [self getTargetPathForFile:filename path:folder];
NSString* fname = [target lastPathComponent];
while ([[NSFileManager defaultManager] fileExistsAtPath: [folder stringByAppendingPathComponent:fname]])
{
//NSLog(@"FNAME : %@",fname);
if ([self str:fname containsString:@")." options:nil])
{
NSArray* a = [fname componentsSeparatedByString:@"("];
NSArray* b = [[a objectAtIndex:1] componentsSeparatedByString:@")"];
fname = [NSString stringWithFormat:@"%@(%d)%@",[a objectAtIndex:0],[[b objectAtIndex:0] intValue]+1,[b objectAtIndex:1]];
}
else
{
fname = [NSString stringWithFormat:@"%@ (1).%@",[fname stringByDeletingPathExtension],[fname pathExtension]];
}
//NSLog(@"Setting filename to :: %@",fname);
}
target = [folder stringByAppendingPathComponent:fname];
Any ideas how to go about this? Is there any Cocoa-friendly (or built-in) method for this?
Why not try this one :