NSMutableArray按顺序添加对象 [英] NSMutableArray add object with order
问题描述
我有一个NSMUtableArray
,其中包含元素,例如:
I have a NSMUtableArray
which has elements, for example:
a,b,c,e
我想在c
之后和e
之前添加对象d
.
换句话说,我想将一个对象插入已排序的数组中(该对象也可以是自定义对象)
And I want to add an object d
to behind c
and before e
.
In other words, I'd like to insert an object to a sorted array.(The object can be a custom object, too)
我想知道:除了使用for
查找位置外,还有其他方法可以实现吗?最好使用iOS api.
I'd like to know : besides using for
to find the position, is there any other method to implement it? It is better to use the iOS api.
谢谢.
推荐答案
You can use -[NSArray indexOfObject:inSortedRange:options:usingComparator:]
to ask an NSArray for the index where an object should be inserted given an array range that’s currently sorted.
例如,假设整个数组都已排序:
For example, assuming the entire array is sorted::
NSMutableArray *array = …;
id newObject = …;
NSComparator comparator = …;
NSUInteger newIndex = [array indexOfObject:newObject
inSortedRange:(NSRange){0, [array count]}
options:NSBinarySearchingInsertionIndex
usingComparator:comparator];
[array insertObject:newObject atIndex:newIndex];
由于此方法使用二进制搜索,因此它比遍历数组中的所有元素更有效.
Since this method uses binary search, it is more efficient than iterating over all elements in the array.
比较器是一个块对象,它接收两个id
类型的对象并返回NSComparisonResult
值.
The comparator is a block object that receives two objects of type id
and returns an NSComparisonResult
value.
这篇关于NSMutableArray按顺序添加对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!