目标c-将NSString与数组的NSString字段相匹配



我有一个名为myObjectArray的NSMutableArray,它包含名为myObject的NSObjects数组。myObject有两个字段(元素?),它们是NSString的。像这样:

@interface myObject : NSObject {
   NSString * string1;
   NSString * string2;
}

我有一个NSMutableArray,它包含大约50个这样的对象,它们都有不同的字符串1和字符串2。那么我有一个独立的NSString变量,叫做otherString;

有没有一种快速的方法可以从字符串1与其他字符串匹配的myObjectArray访问myObject?

我应该说,这就是我所拥有的,但我想知道是否有更快的方法:

-(void) matchString: {
    NSString * testString = otherString;
    for(int i=0; i<[myObjectArray count];i++){
    myObject * tempobject = [myObjectArray objectAtIndex:i];
        NSString * tempString = tempobject.string1;
        if ([testString isEqualToString:tempString]) {
            // do whatever
        }
    }
}

有几种方法可以做到这一点,

使用谓词

NSPredicate * filterPredicate = [NSPredicate predicateWithFormat:@"string1 MATCHES[cd] %@", otherString];
NSArray * filteredArray = [myObjectArray filteredArrayUsingPredicate:filterPredicate];

现在,filteredArray具有其string1otherString匹配的所有myObject实例。

使用indexOfObjectPassingTest:

NSUInteger index = [myObjectArray indexOfObjectPassingTest:^(BOOL)(id obj, NSUInteger idx, BOOL *stop){
    myObject anObject = obj;
    return [anObject.string1 isEqualToString:otherString];
}

如果有一个对象满足条件,index会将您指向它的索引。否则它将具有值NSNotFound

如果希望所有对象都满足条件,也可以查看indexesOfObjectsPassingTest:

最新更新