nal*_*all 2 cocoa objective-c nsdictionary
我有一种情况,我想将一对对象映射到信息字典.我想避免创建NSDictionaries NSDictionaries的NSDictionary,因为这简直令人困惑且难以维护.
例如,如果我有两个类,Foo和Bar,我想要{Foo,Bar} - > {NSDictionary}
除了根据这两种类型制作自定义类(只是用作字典键)之外,还有其他选择吗?也许类似于STL的配对类型,我只是不知道?
就像你说的,你可以创建一个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)
编辑:
关于创建可以是键的对象的一些注意事项:
NSCopying协议,因为我们不希望密钥从我们下面改变.isEqual:.我实施该hash方法以获得良好的衡量标准,但可能没有必要.| 归档时间: |
|
| 查看次数: |
2446 次 |
| 最近记录: |