1

我想为 NSObject 生成一个 MD5 哈希:

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

最好的方法是什么?我已经看到了从字典或数组进行散列的示例,但没有从整个 NSObject 中看到。

4

2 回答 2

5

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

模型.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

模型.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];
于 2013-10-10T20:55:15.863 回答
0

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

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

或者你可以<NSCoding>在你的类上实现,归档它并对结果数据进行散列。

于 2013-10-10T20:31:23.513 回答