Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"sortedArrayHint" method of NSArray class, what is the purpose of this method and how is it used?

Tags:

objective-c

Question is the same as the title. ("sortedArrayHint" method of NSArray class, what is the purpose of this method and how is it used)

I read documentation but the explanation is not clear.

Please explain the purpose of this method and its usage.

like image 833
S.J. Lim Avatar asked Aug 11 '11 08:08

S.J. Lim


People also ask

How do I add elements to NSArray?

If you create an NSArray you won't be able to add elements to it, since it's immutable. You should try using NSMutableArray instead. Also, you inverted the order of alloc and init . alloc creates an instance and init initializes it.

Is NSArray ordered?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.

Is NSMutableArray ordered?

The answer is yes, the order of the elements of an array will be maintained - because an array is an ordered collection of items, just like a string is an ordered sequence of characters...


1 Answers

The idea is simple. Assume you have a large array that should always be sorted. Changing or inserting even one element means you have to resort the array. Sorting is costly.

The method -[NSArray sortedArrayHint] can be called on an already sorted array in order to get private internal data that can be used to speed up a sort of the same array given that only a small change has been made.

Usage is simple:

  1. Get and store the hint from the original sorted array using -[NSArray sortedArrayHint].
  2. After a small change; resort using -[NSArray sortedArrayUsingFunction:context:hint:] with the stored hint.
  3. After a large change; resort using -[NSArray sortedArrayUsingFunction:context:], and get a new hint.

What is a small, or large, change is something you must measure with Instruments.

I never use this myself, since I have found it more effective to use my own categories on NSArray and NSMutabelArray for sorted inserts, that uses a binary search, on sorted array. My code is available as open source here: https://github.com/Jayway/CWFoundation

like image 180
PeyloW Avatar answered Nov 15 '22 05:11

PeyloW