我应该如何构建具有多个键的NSDictionary?

nal*_*all 2 cocoa objective-c nsdictionary

我有一种情况,我想将一对对象映射到信息字典.我想避免创建NSDictionaries NSDictionaries的NSDictionary,因为这简直令人困惑且难以维护.

例如,如果我有两个类,Foo和Bar,我想要{Foo,Bar} - > {NSDictionary}

除了根据这两种类型制作自定义类(只是用作字典键)之外,还有其他选择吗?也许类似于STL的配对类型,我只是不知道?

Dav*_*ong 5

就像你说的,你可以创建一个Pair类:

//Pair.h
@interface Pair : NSOpject <NSCopying> {
  id<NSCopying> left;
  id<NSCopying> right;
}
@property (nonatomic, readonly) id<NSCopying> left;
@property (nonatomic, readonly) id<NSCopying> right;
+ (id) pairWithLeft:(id<NSCopying>)l right:(id<NSCopying>)r;
- (id) initWithLeft:(id<NSCopying>)l right:(id<NSCopying>)r;
@end

//Pair.m
#import "Pair.h"
@implementation Pair
@synthesize left, right;

+ (id) pairWithLeft:(id<NSCopying>)l right:(id<NSCopying>)r {
 return [[[[self class] alloc] initWithLeft:l right:r] autorelease];
}

- (id) initWithLeft:(id<NSCopying>)l right:(id<NSCopying>)r {
  if (self = [super init]) {
    left = [l copy];
    right = [r copy];
  }
  return self;
}

- (void) finalize {
  [left release], left = nil;
  [right release], right = nil;
  [super finalize];
}

- (void) dealloc {
  [left release], left = nil;
  [right release], right = nil;
  [super dealloc];
}

- (id) copyWithZone:(NSZone *)zone {
  Pair * copy = [[[self class] alloc] initWithLeft:[self left] right:[self right]];
  return copy;
}

- (BOOL) isEqual:(id)other {
  if ([other isKindOfClass:[Pair class]] == NO) { return NO; }
  return ([[self left] isEqual:[other left]] && [[self right] isEqual:[other right]]);
}

- (NSUInteger) hash {
  //perhaps not "hashish" enough, but probably good enough
  return [[self left] hash] + [[self right] hash];
}

@end
Run Code Online (Sandbox Code Playgroud)

编辑:

关于创建可以是键的对象的一些注意事项:

  1. 他们必须遵守NSCopying协议,因为我们不希望密钥从我们下面改变.
  2. 由于复制了Pair本身,因此我确保复制了对中的对象.
  3. 密钥必须实现isEqual:.我实施该hash方法以获得良好的衡量标准,但可能没有必要.

  • 如果你实现isEqual:你必须实现-hash.不变量是如果[a isEqual:b],则[哈希]必须== [b哈希]. (3认同)