ios NSPerdicate String获取数组中的第n项

vngu2lb8  于 2023-06-07  发布在  iOS
关注(0)|答案(2)|浏览(407)

我找不到一种方法来使用NSPredicate字符串获取数组中的第 n 项。例如:

//You cannot touch or modify the code inside this method. You can only use the predicate string param to filter the array.
- (NSArray *)filterUsingNSPredicate:(NSString *)PredicateString 
{
    NSArray *array = @[
        @"firstItem",
        @"secondItem",
        @"thirdItem",
        @"fourthItem",
    ];

    NSPredicate *pred = [NSPredicate predicateWithFormat:PredicateString];
    NSArray *filtered = [array filteredArrayUsingPredicate:pred];
    NSLog(@"This is the second item in the array! %@",filtered); //Thats the only thing in the array.
    return filtered;
}
np8igboo

np8igboo1#

如果你想得到一个项目,你不会收到一个NSArray,因为你只会收到一个对象。
可以使用NSPerdicate在数组中按对象的名称进行搜索。但你所说的,并不是你想要的。
您可以使用[array objectAtIndex:index];,它返回位于索引中指定位置的对象。
如果你想要一个对象的索引,你可以使用[array indexOfObject:object];,它返回对象的索引。

ocebsuys

ocebsuys2#

你可以像这样用块www.example.com创建 predicate https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSPredicate_Class/#//apple_ref/occ/clm/NSPredicate/predicateWithBlock%3A,以获得第6个元素(从0开始计数,索引为5):

__block NSInteger index = 0;
NSPredicate *pred = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary<NSString *, id> *bindings)(
    return index++ == 5;
)];

相关问题