differenceFromArray:withOptions:
Compares two arrays, with options, to create a difference object that represents the changes between them.
Declaration
- (NSOrderedCollectionDifference<id> *) differenceFromArray:(NSArray<id> *) other withOptions:(NSOrderedCollectionDifferenceCalculationOptions) options;Discussion
The difference method creates the difference object by comparing objects within the arrays with the isEqual: method.
The options allow you to choose to omit insertion or removal references to the change objects within the difference object. You can also choose to infer moves when computing the difference, which provides an associatedIndex within the change objects that indicates the index in the array where the object moved from.
The following example computes the difference between two arrays, inferring moves between them:
NSArray *original = @[@"Red", @"Green", @"Blue"];
NSArray *modified = @[@"Red", @"Blue", @"Green"];
NSOrderedCollectionDifference *diff = [original
differenceFromArray:modified
withOptions:NSOrderedCollectionDifferenceCalculationInferMoves];
// diff.hasChanges == TRUE
// diff.insertions.count == 1
// diff.removals.count == 1
// Inferring the moves adds an associatedIndex into the change.
NSOrderedCollectionChange* insertion = diff.insertions[0];
// insertion.index == 2
// insertion.associatedIndex == 1
NSOrderedCollectionChange* deletion = diff.removals[0];
// deletion.index == 1
// deletion.associatedIndex == 2