I'm trying to create unique file names by renaming them using their hashed value in iOS. How can I do that?
Asked
Active
Viewed 5,415 times
3 Answers
8
you could achieve this by extending NSString, Try this in your .h:
@interface NSString(MD5)
- (NSString *)generateMD5Hash
@end
and this in your .m
- (NSString*)generateMD5Hash
{
const char *string = [self UTF8String];
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
CC_MD5(string, strlen(string), md5Buffer);
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x",md5Buffer[i]];
return output;
}
you can implement this by making a new class called NSString+MD5, and inserting the code above in the corresponding files (.h and .m)
EDIT: Do not forget to import
< CommonCrypto/CommonDigest.h >
EDIT 2:
And for NSData;
@interface NSData(MD5)
- (NSString *)generateMD5Hash;
@end
your .m:
- (NSString *)generateMD5Hash
{
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
CC_MD5(self.bytes, (CC_LONG)self.length, md5Buffer);
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x",md5Buffer[i]];
return output;
}
Please note that the value returned is autorelease and might need to be retained by the receiver.
Hope this helps.

Jasper
- 7,031
- 3
- 35
- 43

bmeulmeester
- 1,117
- 12
- 26
-
1I'd change this to use an NSData instead, since that's what you get when reading a file. It's trivial to get a const char array from a NSData. – August Lilleaas Oct 03 '11 at 07:38
-
Thanks @August Lilleaas! I implemented this solution and it worked. – tommi Oct 03 '11 at 15:25
1
Why don't you simply generate unique identifiers and use it? like
CFUUIDRef uuidObj = CFUUIDCreate(nil);
NSString *uniqueId = (NSString*)CFUUIDCreateString(nil, uuidObj);
CFRelease(uuidObj);
NSLog(@"%@",uniqueId);
[uniqueId autorelease];

Saran
- 6,274
- 3
- 39
- 48
-
Hey thanks for your answer, decided to use the above solution. Thanks anyway! – tommi Oct 03 '11 at 15:25
0
Using NSData is an expensive choice. Better use NSFileHandler extension if you are dealing with big files anytime.

Gihan
- 2,476
- 2
- 27
- 33