So there's a number of ways to run all the elements of an array through a selector or block of code. makeObjectsPerformSelector:
and more
If you have 4 or 16 cores on hand, you may well want to send all the processing off to differen开发者_开发技巧t processes.
Even on iOS, it could well be sensible to send them all away, or at least let them be finished whichever way the wind blows.
What is the best and neatest way to do this in the cocoa milieu?
Again, what if you want to send them away to be finished at any time, i.e., do not wait for the enumeration to finish before executing the following instruction...?
If you want concurrency and synchronous behaviour (i.e., wait for the enumeration to finish before executing the following instruction), -[NSArray enumerateObjectsWithOptions:usingBlock:]
will do that if you pass the NSEnumerationConcurrent
option. This method is available on Mac OS 10.6+ and iOS 4.0+.
If you want asynchronous behaviour, you can use one of the standard multithreading solutions such as NSOperation or GCD combined with -enumerateObjectsWithOptions:usingBlock:
. For instance,
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[array enumerateObjectsWithOptions:NSEnumerationConcurrent
usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
// do something with obj
}];
});
If you can target iOS 4+ or Mac OS X 10.6+, use Grand Central Dispatch (and I'm using a category because I think they're cool):
#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)];
Or, if you don't want to use a category...
[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL * stop) {
dispatch_async(dispatch_get_global_queue(0,0), ^{
[obj performSelector:@selector(doFoo)];
};
}];
精彩评论