我有一个名为myObjectArray的NSMutableArray,它包含一个名为myObject的NSObjects数组。myObject有两个字段(元素?)它们是NSString的。就像这样:
@interface myObject : NSObject {
NSString * string1;
NSString * string2;
}我有一个包含大约50个这样的对象的NSMutableArray,所有这些对象都有不同的字符串1和字符串2。然后我有一个独立的NSString变量,称为otherString;
有没有一种快速方法可以从myObjectArray访问string1与otherString匹配的otherString?
我应该说,这就是我所拥有的,但我想知道是否有更快的方法:
-(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
}
}
}发布于 2011-06-24 14:13:05
有几种方法可以做到这一点,
使用谓词的
NSPredicate * filterPredicate = [NSPredicate predicateWithFormat:@"string1 MATCHES[cd] %@", otherString];
NSArray * filteredArray = [myObjectArray filteredArrayUsingPredicate:filterPredicate];现在,filteredArray拥有其string1与otherString匹配的所有myObject实例。
使用 的
NSUInteger index = [myObjectArray indexOfObjectPassingTest:^(BOOL)(id obj, NSUInteger idx, BOOL *stop){
myObject anObject = obj;
return [anObject.string1 isEqualToString:otherString];
}如果存在满足条件的对象,index会将您指向其索引。否则,它的值将为NSNotFound。
如果希望所有对象都满足条件,也可以查看indexesOfObjectsPassingTest:。
https://stackoverflow.com/questions/6463975
复制相似问题