iOS:如何在已排序的NSMutableArray中查找插入位置 [英] iOS: How to find insertion position in sorted NSMutableArray

查看:284
本文介绍了iOS:如何在已排序的NSMutableArray中查找插入位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSMutableArray的排序对象,它们显示在UITableView中。

I have an NSMutableArray of sorted objects, which are displayed in a UITableView.

我想在数组中插入一个新对象并更新表视图 - 需要新插入对象的索引。

I want to insert a new object into the array and update the table view - which requires the index of the newly inserted object.

我找不到任何系统消息告诉我正确的插入索引到数组中我需要更新表视图。

I can't find any system message to tell me the correct insertion index into the array which I need to update the table view.

我能找到的最好的是:


  • 添加新对象

  • sort

  • 使用旧的数组副本,找到新对象的位置(需要搜索)


  • 写我自己的插入位置搜索

当然,必须有消息才能在排序数组中找到插入位置?或者我错过了一些明显的东西吗?

Surely, there must be a message to find the insertion position in a sorted array? Or am I missing something obvious here?

推荐答案

您可以使用 indexOfObject:inSortedRange:options:usingComparator: 整个数组的方法。此方法对您传递的范围执行二进制搜索,并在您使用 NSBinarySearchingInsertionIndex 选项时为您提供插入点:

You can use indexOfObject:inSortedRange:options:usingComparator: method on the entire array. This method performs a binary search on a range that you pass, and gives you the insertion point when you use the NSBinarySearchingInsertionIndex option:

NSUInteger insPoint = [myArray
    indexOfObject:toInsert
    inSortedRange:NSMakeRange(0, [myArray count])
    options:NSBinarySearchingInsertionIndex
    usingComparator:^(id lhs, id rhs) {
        return // return the result of comparing two objects
    }
];

这篇关于iOS:如何在已排序的NSMutableArray中查找插入位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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