我的基于块的解决方案可能看起来有点矫枉过正,但如果您有几个这样的要求,它可能会有所帮助:
在 NSArray 上创建一个类别:
@interface NSArray (FunctionalTools)
- (NSArray *)arrayByPerformingBlock:(id (^)(id element))performBlock;
@end
@implementation NSArray (FunctionalTools)
- (NSArray *)arrayByPerformingBlock:(id (^)(id element))performBlock
{
NSMutableArray *array = [NSMutableArray array];
for (id element in self){
[array addObject:performBlock(element)];
}
return array;
}
@end
并像这样使用它:
#import "NSArray+FunctionalTools.h"
//....
self.youtubeVideos = [NSArray arrayWithObjects:
@"http://example.com/index.php?number=1&keyword=",
@"http://example.com/index.php?number=2&keyword=",
nil];
self.youtubeVideos = [youtubeVideos arrayByPerformingBlock:^id(id element) { return [element stringByAppendingString:@"KeyWord"];}];
NSLog(@"%@", youtubeVideos);
甚至
self.youtubeVideos = [[NSArray arrayWithObjects:
@"http://example.com/index.php?number=1&keyword=",
@"http://example.com/index.php?number=2&keyword=",
nil] arrayByPerformingBlock:^id(id element) { return [element stringByAppendingString:@"KeyWord"];}];
我将此示例合并到 sample project 中,我编写该代码是为了自学基于块的技术,以便在 Objective-C 中使用函数式编程。来自 Python 我总是错过像
这样的 List Comprehension
l = ['aa', 'ab','c','ad','dd']
l = [i+i for i in l if i.startswith('a')]
基于块的它看起来像这样:
NSArray *array = [NSArray arrayWithObjects:@"aa", @"ab",@"c",@"ad",@"dd", nil];
array = [array arrayByPerformingBlock:^id(id element) { return [element stringByAppendingString:element]; }
ifElementPassesTest:^BOOL(id element) {return [element hasPrefix:@"a"];}];