あなたが言ったように、ペアクラスを作成できます:
//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
編集:
キーになるオブジェクトの作成に関する注意事項:
NSCopying
キーが私たちの下から変更されたくないので、それらはプロトコルに準拠する必要があります。
- ペア自体がコピーされるため、ペア内のオブジェクトもコピーされるようにします。
- キーは実装する必要があります
isEqual:
。hash
私は適切な方法でこの方法を実装していますが、おそらく必要ではありません。