如果你真的想过滤一个 NSURL 数组,你可以这样做:
- (NSArray *)filteredArray:(NSArray *)originalArray withSubpath:(NSString *)subpath {
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
NSURL *url = (NSURL *)evaluatedObject;
NSRange range = [[url path] rangeOfString:subpath];
return (range.location == 0);
}];
return [originalArray filteredArrayUsingPredicate:predicate];
}
这是我测试它的方法:
NSArray *urls = @[[NSURL URLWithString:@"Animals/Birds/file1.xyz"],
[NSURL URLWithString:@"Animals/Birds/file2.xyz"],
[NSURL URLWithString:@"Animals/Cats/file1.xyz"],
[NSURL URLWithString:@"Cars/Ford/file1.xyz"]];
NSLog(@"Before: %@", urls);
urls = [self filteredArray:urls withSubpath:@"Animals/Birds"];
NSLog(@"After: %@", urls);
输出日志是:
Before: (
"Animals/Birds/file1.xyz",
"Animals/Birds/file2.xyz",
"Animals/Cats/file1.xyz",
"Cars/Ford/file1.xyz"
)
After: (
"Animals/Birds/file1.xyz",
"Animals/Birds/file2.xyz"
)
注意:它匹配子字符串,因此在这种情况下它不会匹配“/Animals”,因为前导斜杠(除非数组和子字符串都包含“/”)。