objective-c - objective-c 中的排序数组或映射?

标签 objective-c ios arrays map

我正在iOS上的Objective-C中搜索排序后的数组或映射(字典...无论如何)。

是否有可比较的东西(在插入时排序),还是我必须重写getter / setter并“自行”对数据结构进行排序?我知道,可以对数组进行排序,但是我想知道是否存在像Java中的TreeMap这样的“自动”方式,您可以在其中放置一个Entry并将其直接插入正确的位置。

干杯,

马克

最佳答案

如果想要一个数组,可能最简单的方法是在NSMutableArray上创建一个在正确位置插入对象的方法。但是,这有点不能令人满意(没有什么可以阻止您使用常规方法插入对象并破坏顺序),因此您可能想要自己的集合类。您可以通过在新类中包装NSMutableArray和comparator轻松地创建此代码。例如

@interface MyOrderedArray : NSObject <NSFastEnumeration>

-(id) initWithComparator: (NSComparator) anOrdering;

-(void) insertObject: (id) aNewObject;

// methods to access objects from the array

@end

@implementation MyOrderedArray
{
   NSComaparator theOrdering;
   NSMutableArray* backingArray;
}

-(id) initWithComparator: (NSComparator) anOrdering
{
    self = [super init];
    if (self != nil)
    {
        theOrdering = [anOrdering copy];
        backingArray = [[NSMUtableArray alloc] init];
}

-(id) insertObject: (id) newObject
{
    // use a binary search to find the index and insert the object there
}

可以将其他方法传递到支持数组以实现例如
-(NSUInteger) count
{
    return [backingArray count];
}

这将是有用的:
- (NSUInteger)countByEnumeratingWithState: (NSFastEnumerationState*) state 
                                  objects: (id*) stackbuf 
                                    count: (NSUInteger) len
{
    return [backingArray countByEnumeratingWithState: state 
                                             objects: stackbuf 
                                               count: len];
}

关于objective-c - objective-c 中的排序数组或映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9994401/

相关文章:

ios - cordova::XMLHttpRequest::setRequestHeader 不适用于 JSONP

ios - UIView:alpha:0、hidden:YES、removeViewFromSuperview 和 frame.origin.y = -100000 之间的性能/内存差异;

ios - 更改边界大小后 CALayer 的位置

java - 在java中插入和反转数组中的元素

ios - 表格单元格文本标签框宽度自动增加

objective-c - ScrollView 中图像之间的差距

objective-c - ARC 是否足够聪明以释放父类(super class)中定义的 subview ?

iphone - __weak UIDataType *weakSelf 和 UIDataType __weak *weakSelf 之间的区别?

C编程: String arrays - how to check equality?

javascript - 复制 N 个 JS 对象并在其中进行更改