Filter array by first letter of string property

后端 未结 6 829
别那么骄傲
别那么骄傲 2020-12-06 05:09

I have an NSArray with objects that have a name property.

I would like filter the array by name

    NSString          


        
相关标签:
6条回答
  • 2020-12-06 05:48

    NSArray offers another selector for sorting arrays:

    NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(Person *first, Person *second) {
        return [first.name compare:second.name];
    }];
    
    0 讨论(0)
  • 2020-12-06 05:50

    Checkout this library

    https://github.com/BadChoice/Collection

    It comes with lots of easy array functions to never write a loop again

    So you can just do

    NSArray* result = [thArray filter:^BOOL(NSString *text) {
        return [[name substr:0] isEqualToString:@"A"]; 
    }] sort];
    

    This gets only the texts that start with A sorted alphabetically

    If you are doing it with objects:

    NSArray* result = [thArray filter:^BOOL(AnObject *object) {
        return [[object.name substr:0] isEqualToString:@"A"]; 
    }] sort:@"name"];
    
    0 讨论(0)
  • 2020-12-06 05:58

    Here is one of the basic use of NSPredicate for filtering array .

    NSMutableArray *array =
    [NSMutableArray arrayWithObjects:@"Nick", @"Ben", @"Adam", @"Melissa", @"arbind", nil];
    
    NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'b'"];
    NSArray *beginWithB = [array filteredArrayUsingPredicate:sPredicate];
    NSLog(@"beginwithB = %@",beginWithB);
    
    0 讨论(0)
  • 2020-12-06 05:59

    If you want to filter array take a look on this code:

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", @"qwe"];
    NSArray *result = [self.categoryItems filteredArrayUsingPredicate:predicate];
    

    But if you want to sort array take a look on the following functions:

    - (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context;
    - (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context hint:(NSData *)hint;
    - (NSArray *)sortedArrayUsingSelector:(SEL)comparator;
    
    0 讨论(0)
  • 2020-12-06 06:01

    Try with following code

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF like %@", yourName];
    NSArray *filteredArr = [yourArray filteredArrayUsingPredicate:pred];
    

    EDITED :

    NSPredicate pattern should be:

    NSPredicate *pred =[NSPredicate predicateWithFormat:@"name beginswith[c] %@", alphabet];
    
    0 讨论(0)
  • 2020-12-06 06:05

    visit https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Collections/Articles/Arrays.html

    use this

    [listArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    
    0 讨论(0)
提交回复
热议问题