2 // NSFileManager+UniqueNames.m
5 // Created by Joe Wreschnig on 3/7/13.
9 #import "NSFileManager+UniqueNames.h"
11 @implementation NSFileManager (UniqueNames)
13 - (NSURL *)generateUniqueURLWithBase:(NSURL *)canonical {
14 // Punt for cases that are just too hard.
15 if (!canonical.isFileURL)
18 NSString *trying = canonical.path;
19 NSString *dirname = [trying stringByDeletingLastPathComponent];
20 NSString *basename = [trying.lastPathComponent stringByDeletingPathExtension];
21 NSString *extension = trying.pathExtension;
23 while ([self fileExistsAtPath:trying] && index < 10000) {
24 NSString *indexName = [NSString stringWithFormat:@"%@ (%d)", basename, index++];
25 indexName = [indexName stringByAppendingPathExtension:extension];
26 trying = [dirname stringByAppendingPathComponent:indexName];
28 return [NSURL fileURLWithPath:trying];