开发者

sorted array from indexesOfObjectsPassingTest?

I have an array of myObjects called arrayToFilter. One (element?) of myObject is an array of bezierpaths. I am comparing the bezierpath at a particular index (thispath) to a second path, and making filteredArray composed of only those objects in which the paths overlapped a certain amount (20%). I used indexedOfObjectsPassingTest to like this:

    NSIndexSet * index = [[arrayToFilter objectsAtIndexes:index]       indexesOfObj开发者_如何学GoectsPassingTest:^BOOL (id obj, NSUInteger idx, BOOL *stop){
    MyObject * anobject = obj;
        UIBezierPath * thispath = [anobject.allPaths objectAtIndex:i];
        NSInteger  overlap = [self percentPathBoxOverlap:path: thispath];

        return overlap>20;
    }];

    if ([index count] !=0){
        filteredArray = [arrayToFilter objectsAtIndexes:index] ;
    }

This works fine. But what i'd like to do is have filteredArray come out sorted with those object with the higher value for overlap coming out first. since overlap is calculated on the fly based on the current path and thispath, i don't know how to use any of the sorted array methods.


You can start off by creating an array of dictionaries containing both path and the overlap data. This will require some modification to your current approach where you search and extract over filter.

NSMutableArray * searchResults = [NSMutableArray array];
[arrayToSearch enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
   MyObject     * anobject = obj;
   UIBezierPath * thispath = [anobject.allPaths objectAtIndex:i];

   NSInteger  overlap = [self percentPathBoxOverlap:path: thispath]; 

   if ( overlap > 20 ) {
       NSMutableDictionary * dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:anObject, @"object", [NSNumber numberWithInteger:overlap], @"overlap", nil];
       [searchResults addObject:dictionary];
   }
}];

Now you can sort this array using the overlap key of the dictionaries.

NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey:@"overlap" ascending:NO];
NSArray * sortedArray = [searchResults sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];

Now sortedArray will have the sorted list of path and overlap information.


You'll have to sort the array first, then call indexesOfObjectsPassingTest for the sorted indices. sortedArrayUsingComparator: is one of the easier methods of sorting an array, it takes a block just like the indexesOfObjectsPassingTest method.

NSArray arrayToFilter = [originalArray sortedArrayUsingComparator: ^(id a, id b) 
{ 
  if (a.someValue > b.someValue) return NSOrderedAscending; 
  if (a.someValue < b.someValue) return NSOrderedDescending;
  return NSOrderedSame;
}];

Then you can perform your existing filtering on the arrayToFilter

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜