我正在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/