objective-c - 是否有像 C++ STL 的 `transform` 这样的 Objective-C 算法?

标签 objective-c arrays algorithm

我的目标是拥有一个数组,其中包含特定扩展名的所有文件名,但没有扩展名。

有一个 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/

相关文章:

objective-c - NSParagraphStyle 行间距被忽略

ios - UIStackView child 等距(周围和之间)

ios - 新的 FBSDK 4.0+,使用访问 token 登录或共享

arrays - 将 ls 输出转换为数组

c++ - 使用函数调用更改数组的值

arrays - 将二维数组旋转 90 度

无替换采样算法?

ios - AVaudioPlayer 不工作,mp3 位于编译包中

c++ - 在二叉搜索树中寻找最小和的算法改进

algorithm - Spark : Counting co-occurrence - Algorithm for efficient multi-pass filtering of huge collections