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.
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.
An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.
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...
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:
-[NSArray sortedArrayHint]
.-[NSArray sortedArrayUsingFunction:context:hint:]
with the stored hint.-[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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With