NSSortDescriptor issue

前端 未结 4 1977
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-13 20:24

I am making a contact book App where I am fetching names from AddressBook and stored them in Core data and displayed the names on a table using NSFetchedResultsControl

4条回答
  •  清酒与你
    2021-01-13 21:11

    You could split up the results into two arrays, one that starts with alpha characters, and one that doesn't. Then just add the two together. Assuming you are starting with an array of managed objects called results:

    //Create the sort descriptor array
    NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"fullName" ascending:YES];
    NSArray *descriptors = [NSArray arrayWithObject:sd];
    
    //Create a sorted array of objects where fullName starts with an alpha character
    //using a Regex
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"fullName MATCHES '^[a-zA-Z].*'"];
    
    NSArray *alpha = [[results filteredArrayUsingPredicate:pred] sortedArrayUsingDescriptors:descriptors];
    
    //Now use the alpha array to create an array of objects where the fullName does not
    //start with an alpha character
    
    NSMutableArray *nonAlpha = [results mutableCopy];
    
    [nonAlpha removeObjectsInArray:alpha];
    
    [nonAlpha sortUsingDescriptors:descriptors];
    
    //Now put them back together again
    
    NSArray *sortedResults = [alpha arrayByAddingObjectsFromArray:nonAlpha];
    
    //And if you're not using ARC!
    [nonAlpha release];
    

提交回复
热议问题