Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a unique string used for saving data

Tags:

ios

iphone

I'm building an application for the iphone. I scan the iPod library and bring in all the album art. I need a way of creating a unique string so that when I'm saving the album art to the documents directory, each file has a unique name. Does anyone know to create a unique string? Thanks in advance.

like image 391
Darren Findlay Avatar asked Mar 17 '11 17:03

Darren Findlay


People also ask

How do you generate unique random strings?

There are many ways to generate a random, unique, alphanumeric string in PHP which are given below: Using str_shuffle() Function: The str_shuffle() function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter.

How do you make a string unique in Java?

Using randomUUID() UUID is another Java class that can be used to generate a random string. It offers a static randomUUID() method that returns a random alphanumeric string of 32 characters.

How do you generate unique strings in SQL Server?

If you need a string of random digits up to 32 characters for test data or just need some junk text to fill a field, SQL Server's NEWID() function makes this simple. NEWID() is used to create a new GUID (globally unique identifier), and we can use that as a base to get a string of random characters.


2 Answers

I use this code:

+ (NSString *)getUniqueFilenameInFolder:(NSString *)folder forFileExtension:(NSString *)fileExtension {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *existingFiles = [fileManager contentsOfDirectoryAtPath:folder error:nil];
    NSString *uniqueFilename;

    do {
        CFUUIDRef newUniqueId = CFUUIDCreate(kCFAllocatorDefault);
        CFStringRef newUniqueIdString = CFUUIDCreateString(kCFAllocatorDefault, newUniqueId);

        uniqueFilename = [[folder stringByAppendingPathComponent:(NSString *)newUniqueIdString] stringByAppendingPathExtension:fileExtension];

        CFRelease(newUniqueId);
        CFRelease(newUniqueIdString);
    } while ([existingFiles containsObject:uniqueFilename]);

    return uniqueFilename;
}

Maybe it helps someone. :-)

Keep in mind, that this returns the full path of the unique file. You might want to add some small changes to just return the filename. For example if you want to persist it somewhere.

like image 79
thomas Avatar answered Sep 29 '22 23:09

thomas


You want to be creating a GUID or UUID, which is a 128-bit integer that has a string associated with it. Check out http://developer.apple.com/library/ios/#documentation/CoreFoundation/Reference/CFUUIDRef/Reference/reference.html

like image 41
Bleaourgh Avatar answered Sep 29 '22 23:09

Bleaourgh