如何处理数组IN PARALLEL

Fat*_*tie 8 iphone cocoa

因此,有许多方法可以通过选择器或代码块运行数组的所有元素.makeObjectsPerformSelector:和更多

如果您手头有4个或16个核心,您可能希望将所有处理发送到不同的进程.

即使在iOS上,将它们全部发送出去也是明智之举,或者至少让它们以风的方式完成.

可可环境中最好和最好的方法是什么?

再次,如果你想将它们发送到任何时候完成,即在执行以下指令之前不要等待枚举完成,该怎么办?

小智 10

如果您想要并发和同步行为(即,在执行以下指令之前等待枚举完成),-[NSArray enumerateObjectsWithOptions:usingBlock:]如果您通过该NSEnumerationConcurrent选项,则会执行此操作.此方法适用于Mac OS 10.6+和iOS 4.0+.

如果您想要异步行为,可以使用标准多线程解决方案之一,如NSOperation或GCD结合使用-enumerateObjectsWithOptions:usingBlock:.例如,

dispatch_async(dispatch_get_global_queue(0, 0), ^{
    [array enumerateObjectsWithOptions:NSEnumerationConcurrent
        usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            // do something with obj
        }];
    });
Run Code Online (Sandbox Code Playgroud)


Dav*_*ong 9

如果您可以定位iOS 4+或Mac OS X 10.6+,请使用Grand Central Dispatch(我正在使用一个类别,因为我觉得它们很酷):

#import <dispatch/dispatch.h>

@interface NSArray (DDAsynchronousAdditions)

- (void) makeObjectsPerformSelectorAsynchronously:(SEL)selector;
- (void) makeObjectsPerformSelectorAsynchronously:(SEL)selector withObject:(id)object;

@end

@implementation NSArray (DDAsynchronousAdditions)

- (void) makeObjectsPerformSelectorAsynchronously:(SEL)selector {
  [self makeObjectsPerformSelectorAsynchronously:selector withObject:nil];
}

- (void) makeObjectsPerformSelectorAsynchronously:(SEL)selector withObject:(id)object {
  for (id element in self) {
    dispatch_async(dispatch_get_global_queue(0,0), ^{
      [element performSelector:selector withObject:object];
    });
  }
}

@end

//elsewhere:

[myArray makeObjectsPerformSelectorAsynchronously:@selector(doFoo)];
Run Code Online (Sandbox Code Playgroud)

或者,如果您不想使用类别......

[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL * stop) {
  dispatch_async(dispatch_get_global_queue(0,0), ^{
    [obj performSelector:@selector(doFoo)];
  };
}];
Run Code Online (Sandbox Code Playgroud)

  • @Jon nope.这是大中央调度的全部*点*.它在全局线程上排队,并在执行时执行. (2认同)