简体   繁体   English

如何使用NSPredicate过滤这些NSArray?

[英]How to filter these NSArray with NSPredicate?

-(void) vUpdateHistoryAndSuggestionEntries
{
    NSArray * potentialHistory = [[self class] arHistory];
}

potentialHistory is an array of NSString objects. potentialHistory是NSString对象的数组。

I want to filter only elements that start with, for example, @"Cat" in case insensitive manner.For example, 我只想以不区分大小写的方式过滤以@开头的元素,例如@“ Cat”。例如,

if the NSArray contains 如果NSArray包含

Cathy Cat Dog 凯茜猫狗

Then I want an array that contains 然后我想要一个包含

Cathy Cat 凯茜猫

I think NSPredicate is ideal for this. 我认为NSPredicate对此非常理想。 Any other ways will be fine too. 任何其他方式也可以。

There are similar questions. 有类似的问题。 However, in those questions, NSArray contains dictionary. 但是,在这些问题中,NSArray包含字典。 I want to filter based on the actual element of the array instead of element of element of the array. 我想基于数组的实际元素而不是数组元素的元素进行过滤。

NSArray *yourArray;
NSPredicate *aPredicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'C'"];
NSArray *theFilteredArray = [yourArray filteredArrayUsingPredicate:aPredicate];

Hope this will help you. 希望这会帮助你。

Here's an example of how to use NSPredicate: 这是有关如何使用NSPredicate的示例:

NSArray *sampleArray = @[@"Cathy", @"Cat", @"Dog"];
NSArray *filteredSampleArray = [sampleArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self contains[c] %@",@"ca"]];
NSLog(@"%@",filteredSampleArray);

This will output: 这将输出:

( Cathy, Cat ) (凯茜,猫)

NSString *filterStr = [NSString stringWithFormat:@"name LIKE[c] '*%1$@*'",searchStr];
NSPredicate *predicate = [NSPredicate predicateWithFormat:filterStr];
NSMutableArray *tempArray = [yourArrayofNames filteredArrayUsingPredicate:predicate];

//here name is your property and yourArrayofNames is your array of objects. //这里name是您的属性,yourArrayofNames是您的对象数组。

You do not need NSPredicate for simply this. 您不必为此简单地使用NSPredicate

for (NSString* item in arHistory){

    if ([item rangeOfString:@"cat" options:NSCaseInsensitiveSearch].location == 0){//occurs at beginning

        [potentialHistory addObject:item];
    }
}

EDIT: If potentialHistory is immutable, use another array to store these and init potentialHistory with it. 编辑:如果potentialHistory是不可变的,请使用另一个数组来存储它们,并使用它来init potentialHistory。

NSArray* potentialArray = [NSArray arrayWithArray:(NSArray*)array]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM