Note that there are some explanatory texts on larger screens.

plurals
  1. POObjective-C Fastest Way to find Closest NSDate in NSArray
    primarykey
    data
    text
    <p>I pass in an NSDate to the following function and want to find the NSDate in the array that is closest in time to the passed in value. </p> <p>Please note that I do not want to know if the array contains the exact date like this post: <a href="https://stackoverflow.com/questions/18139459/find-nsdate-in-sorted-nsarray">Find NSDate in sorted NSArray</a></p> <p>I want to know which date in the array is nearest in time to my reference date.</p> <p>I must do this frequently. The following works but is slow - how can I speed things up?</p> <pre><code>// Get the XYZ data nearest to the passed time - (eciXYZ)eciDataForTime:(NSDate*)time { // Iterate our list and find the nearest time float nearestTime = 86400; // Maximum size of dataset ( 2 days ) int index = 0; // Track the index int smallestDifferenceIndex = index; // Track the index with the smallest index NSDate *lastListDate; // Track the closest list date for ( index = 0 ; index &lt; [self.time count]-1 ; index++ ) { NSDate *listDate = [self.time objectAtIndex:index]; // Get the date - Time is an NSMutableArray of NSDates // NSTimeInterval is specified in seconds; it yields sub-millisecond precision over a range of 10,000 years. NSTimeInterval timeDifferenceBetweenDates = [listDate timeIntervalSinceDate:time]; if ( timeDifferenceBetweenDates &lt; nearestTime &amp;&amp; timeDifferenceBetweenDates &gt; 0 ) { nearestTime = timeDifferenceBetweenDates; // Update the tracker smallestDifferenceIndex = index; // Update the smallest difference tracker lastListDate = listDate; // Capture the closest date match //NSLog(@"Time: %f %@",timeDifferenceBetweenDates,listDate); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload