从Objective-C对象生成MD5哈希

时间:2013-10-10 20:28:43

标签: ios objective-c hash

我想为NSObject生成MD5哈希:

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * type;
@property (nonatomic, retain) NSString * unit;
@property (nonatomic, retain) NSArray * fields;

最好的方法是什么?我已经看过来自字典或数组的哈希示例,但不是来自整个NSObject的示例。

2 个答案:

答案 0 :(得分:5)

要为NSObject或NSObject的子类生成MD5哈希,您需要将其转换为易于清理但仍代表实例状态的内容。 JSON字符串就是这样一个选项。代码如下所示:

<强> Model.h

#import <Foundation/Foundation.h>

@interface Model : NSObject

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * type;
@property (nonatomic, retain) NSString * unit;
@property (nonatomic, retain) NSArray * fields;

- (NSString *)md5Hash;

@end

<强> Model.m

#import <CommonCrypto/CommonDigest.h>
#import "Model.h"

@implementation Model

- (NSString *)md5Hash
{
    // Serialize this Model instance as a JSON string
    NSDictionary *map = @{ @"name": self.name, @"type": self.type,
                           @"unit": self.unit, @"fields": self.fields };

    NSError *error = NULL;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:map
                                                        options:NSJSONWritingPrettyPrinted
                                                          error:&error];
    if (error != nil) {
        NSLog(@"Serialization Error: %@", error);
        return nil;
    }

    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    // Now create the MD5 hashs
    const char *ptr = [jsonString UTF8String];
    unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];

    CC_MD5(ptr, strlen(ptr), 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;
}

@end

然后,您只需调用md5Hash方法

即可轻松检索MD5哈希
Model *obj = [Model new];
obj.name = @"...";
obj.type = @"...";
obj.unit = @"...";
obj.fields = @[ ... ];

NSString *hashValue = [obj md5Hash];

答案 1 :(得分:0)

如果您已经有用于创建哈希的代码,则可以将对象转换为字典:

NSDictionary *dict = [myObject dictionaryWithValuesForKeys:@[@"name", @"type", @"unit", @"fields"]];

或者您可以在类上实现<NSCoding>,将其存档并对结果数据进行哈希处理。