Reputation: 29896
How can an array of objects be sorted by comparing one of their properties (NSString *
) to objects (already sorted) in another array of (NSString *
)s?
I fill an array of e.g. Person
objects in the order a number of threads happen to complete in. I would then like to compare each Person.name
against an array of name objects that is already ordered. The result would be the Person
array sorted in the same order as the names array by the person.name
property.
Upvotes: 0
Views: 90
Reputation: 4248
Maybe something like that
NSMutableArray *excluded = [NSMutableArray array];
NSArray *sortedNames = @[@"name1", @"name5", @"name3", /*more names*/ @"nameX"];
NSArray *tmp = [inputArray sortedArrayUsingComparator: ^(id p1, id p2) {
NSUInteger pos1 = [sortedNames indexOfObject:((Person *)p1).name];
NSUInteger pos2 = [sortedNames indexOfObject:((Person *)p2).name];
if (pos1 == NSNotFound && ![excluded containsObject:p1]) {
[excluded addObject:p1];
}
if (pos2 == NSNotFound && ![excluded containsObject:p2]) {
[excluded addObject:p2];
}
if (pos1 == pos2) return NSOrderedSame;
if (pos1 > pos2) return NSOrderedDescending;
return NSOrderedAscending;
}];
NSArray *sortedArray = [tmp subarrayWithRange:NSMakeRange(0, [tmp count] - [excluded count])];
Upvotes: 0
Reputation: 1083
You could try something similar to this, with very little details this the best I could come up with:
NSArray *array1 = [NSArray array];
NSArray *sortedArray = [NSArray array];
NSMutableArray *tmpArray = [NSMutableArray array];
for (id object in sortedArray)
{
if ([array1 containsObject:object])
[tmpArray addObject:object];
}
This code loops threw the sorted array and checks if the unsorted array contains that same object. If it does it placed it in tmpArray. When if finishes it will have a sorted array with the items it contained.
Here's a link I found using NSPredicate
for a more optimized solution https://stackoverflow.com/a/2873439/507299.
Upvotes: 1