Last active
August 29, 2015 14:05
-
-
Save frankus/3158821d4b6ed85cfb77 to your computer and use it in GitHub Desktop.
Switch between sorted arrays with intelligent animations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Returns the index paths of the rows affected by switching between two | |
sorted (but not necessarily unique) arrays. | |
@param old The array to be switched from. | |
@param new The array to be switched to. | |
@param keyPath the key path to compare ("@self" to use raw value) | |
@return An array of three arrays, the first containing index paths | |
for modified rows, the second for deleted rows, and the third for | |
inserted rows. | |
*/ | |
- (NSArray *)affectedRowsForSwitchingFromArray:(NSArray *)old toArray:(NSArray *)new keyPath:(NSString *)keyPath { | |
NSInteger i = 0, j = 0; | |
NSMutableArray *indexPathsOfModifiedItems = [NSMutableArray array]; | |
NSMutableArray *indexPathsOfDeletedItems = [NSMutableArray array]; | |
NSMutableArray *indexPathsOfAddedItems = [NSMutableArray array]; | |
while (i < [new count] || j < [old count]) { | |
NSComparisonResult comp; | |
if (i < [new count] && j < [old count]) | |
comp = [[new[i] valueForKeyPath:keyPath] compare:[old[j] valueForKeyPath:keyPath]]; | |
else if (i >= [new count]) | |
comp = NSOrderedDescending; | |
else if (j >= [old count]) | |
comp = NSOrderedAscending; | |
if (comp == NSOrderedSame) { | |
[indexPathsOfModifiedItems addObject:[NSIndexPath indexPathForRow:j inSection:0]]; | |
i++, j++; | |
} else if (comp == NSOrderedAscending) { | |
[indexPathsOfAddedItems addObject:[NSIndexPath indexPathForRow:i inSection:0]]; | |
i++; | |
} else if (comp == NSOrderedDescending) { | |
[indexPathsOfDeletedItems addObject:[NSIndexPath indexPathForRow:j inSection:0]]; | |
j++; | |
} | |
} | |
return @[ indexPathsOfModifiedItems, indexPathsOfDeletedItems, indexPathsOfAddedItems]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment