0

我想从数组中获取一些对象,其中包含对象属性之一满足条件的对象

就像在c#中一样

例子 :

NSMutablearray * coursesinfo ;

该数组包含 30 多个课程

course 是其属性的对象是 finalgrade

我想获得所有课程where final grade < 100

我可以像 c# 一样在 Objective-c 中做到这一点吗?如何?

4

2 回答 2

3

where 语句就像在 cocoa/cocoa touch 中使用谓词一样。这是一个示例,其中我有一个目录中的图像文件名数组,并且我正在寻找基本文件名。indexOfObjectsWithOptions: 方法返回一组通过特定测试的索引。NSEnumerationConcurrent 利用并发队列来利用多个内核(如果存在)。

NSIndexSet *indexSet=[allImageURLs indexesOfObjectsWithOptions:NSEnumerationConcurrent passingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    BOOL match=NO;
    NSRange twoXRange=[((NSURL *)obj).absoluteString rangeOfString:@"@2x"];
    NSRange iPhoneRange=[((NSURL *)obj).absoluteString rangeOfString:@"~ipad"];
    if (twoXRange.location==NSNotFound && iPhoneRange.location==NSNotFound) {
        match=YES;
    }
    return  match;
}];

self.imageURLs=[allImageURLs objectsAtIndexes: indexSet];

对于您的特殊情况,我会执行以下操作:

NSIndexSet *theSet=[coursesinfo indexesOfObjectsWithOptions:NSEnumerationConcurrent passingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    BOOL match=NO;

    if( obj.finalGrade<100 ){
       match=YES;
    }
    return match;
}];

NSArray *courses=[coursesinfo objectsAtIndexes: theSet];

祝你好运!

于 2012-05-27T03:27:09.443 回答
0

最接近的是使用- (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicateNSArray 的函数。

链接到NSPredicate 文档

于 2012-05-27T01:54:09.607 回答