NSMutableArray按顺序添加对象 [英] NSMutableArray add object with order

查看:474
本文介绍了NSMutableArray按顺序添加对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆