我的目标是拥有一个包含特定扩展名的所有文件名但不包含扩展名的数组。
有一个获取特定扩展名的所有文件名的优雅解决方案 https://stackoverflow.com/questions/499673/getting-a-list-of-files-in-a-directory-with-a-glob/907444#907444使用谓词过滤器和有关如何将路径拆分为文件名和扩展名的说明 https://stackoverflow.com/questions/1984572/pathforresource-without-using-extension-iphone/1984605#1984605,但要结合它们,我必须编写一个循环(不可怕,但也不优雅)。
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
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)