如何在iOS上创建文件的哈希? [英] How do I create a hash of a file on iOS?

查看:239
本文介绍了如何在iOS上创建文件的哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过在iOS中使用散列值重命名来创建唯一的文件名。我怎么能这样做?

I'm trying to create unique file names by renaming them using their hashed value in iOS. How can I do that?

推荐答案

你可以通过扩展NSString来实现这个目标,
在你的.h中试试这个:

you could achieve this by extending NSString, Try this in your .h:

@interface NSString(MD5)

- (NSString *)generateMD5Hash

@end

这是你的.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;
}

你可以通过创建一个名为NSString + MD5的新类并插入来实现这一点相应文件中的上述代码(.h和.m)

you can implement this by making a new class called NSString+MD5, and inserting the code above in the corresponding files (.h and .m)

编辑:别忘了导入


< CommonCrypto / CommonDigest.h>

< CommonCrypto/CommonDigest.h >

编辑2:

对于NSData ;

And for NSData;

@interface NSData(MD5)

- (NSString *)generateMD5Hash;

@end

你的.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;
}

请注意,返回的值是autorelease,可能需要保留接收器。

Please note that the value returned is autorelease and might need to be retained by the receiver.

希望这会有所帮助。

这篇关于如何在iOS上创建文件的哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆