Objective-C中两个变量(双精度)的数据结构

时间:2015-04-15 23:15:26

标签: objective-c data-structures nsmutablearray nsarray

我正在寻找最好的数据结构(容器),它只会在Objective-C(Mac OS X或iOS应用程序)中存储两个变量:

-(X) minAndMaxFinder: (NSMutableArray *)dataX {
double maxX = [[dataX valueForKeyPath:@"@max.intValue"] doubleValue];
double minX = [[dataX valueForKeyPath:@"@min.intValue"] doubleValue];
//adding these two variables (minX and maxX) to the structure X, later these data will be used in different methods 
return X;
}

它应该是NSArray还是其他什么? NSDictionary不是必须的解决方案,因为这两个变量不像键值那样必须连接。例如,NSMutableArray可以轻松更改存储的变量,但它也可以添加更多其他变量。可能最好保持限制不要添加其他变量,如NSArray。据我所知,除非集成C ++,否则Objective C中没有向量。

在这种情况下,最推荐哪种解决方案?

1 个答案:

答案 0 :(得分:1)

我在处理一个奇怪的问题时遇到了这个问题,这是最好的解决方案。这不是一个典型的需要,所以考虑找到另一种方法,但是,我有一个非常简单的类我叫做一对。这对我来说是不可改变的,但它不一定适合你。

@interface DGCPair : NSObject

@property (nonatomic, readonly) id first;
@property (nonatomic, readonly) id second;

- (instancetype)initWithFirst:(id)first 
                       second:(id)second;

@end

即使您的实现文件除了init方法以外大部分都是空的,这应该可以满足您的需求。对于可以通过基本数据结构(或者如果我们有它们的元组)可以愉快地完成的事情,这可能有点过分,但它可以完成工作。为了成为字典中的关键,我实施NSCopying,但是,你的不再需要。

所以在你的情况下你可以:

-(DGCPair *)minAndMaxFinder:(NSArray *)dataX {
    double maxX = [[dataX valueForKeyPath:@"@max.intValue"] doubleValue];
    double minX = [[dataX valueForKeyPath:@"@min.intValue"] doubleValue];

    return [[DGCPair alloc] initWithFirst:@(maxX) second:@(minX)];
}

您只需要确保记住或记录哪个物体位于哪个位置(最大值为1,最小值为秒)。