我的目标是拥有一个数组,其中包含特定扩展名的所有文件名,但没有扩展名。
有一个 elegant solution to get all filenames of a specific extension使用谓词过滤器和 instructions on how to split a path into filename and extension ,但要将它们结合起来,我必须编写一个循环(并不糟糕,但也不优雅)。
有没有办法用 Objective-C(可能类似于谓词机制)将一些函数应用于数组的每个元素并将结果放入第二个数组,如 transform
算法C++ STL 的作用是什么?
我想写什么:
// let's pretend 'anArray' was filled by querying the filesystem and not hardcoded
NSArray* anArray = [[NSArray alloc] initWithObjects:@"one.ext", @"two.ext", nil];
// that's what I liked to write (pseudo code)
NSArray* transformed = [anArray transform: stringByDeletingPathExtension];
// Yuji's answer below proposes this (which may be as close as you can get
// to my wish with Objective C)
NSArray* transformed = [anArray my_arrayByApplyingBlock:^(id x){
return [x stringByDeletingPathExtension];
}];
最佳答案
其实有个很简单的方法。它自 2003 年以来一直存在,但命名不当。
NSArray *array = [NSArray arrayWithObjects:@"one.ext", @"two.ext", nil];
// short solution
NSArray *transformed = [array valueForKey:@"stringByDeletingPathExtension"];
// long solution (more robust against refactoring)
NSString *key = NSStringFromSelector(@selector(stringByDeletingPathExtension));
NSArray *transformed = [array valueForKey:key];
两者都产生输出:
(
one,
two
)
关于objective-c - 是否有像 C++ STL 的 `transform` 这样的 Objective-C 算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4579137/