I'm trying to integrate some GCD into my code, and have found that a severe bottleneck is a bubble comparison I am performing between objects in a large array. Here is the original code:
NSUInteger count = [arrayToDoWorkOn count];
for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++)
{
[[arrayToDoWorkOn objectAtIndex:i] compare:[arrayToDoWorkOn objectAtIndex:j]];
}
}
Get my drift? So a lot of other fast enumeration tasks can be easily GCD'd by converting
for (id obj in array)
{
[obj aMessage:stuff];
}
to:
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
[obj aMessage:stuff];
}];
Is there a way to convert my look-ahead-sorta-bubble-sorta-algorithm-thing to something that I can feed to a GCD block implementation?
I wouldn't recommend implementing your own sort if
NSArray
already has a built in method for it that will most likely sort faster than anything you can come up with. You can just use this:Now, if you need to use the objects during the sort, you're in for a pickle, but I'd recommend looking into sorts more efficient than a bubble sort (quick sort is a pretty good one).
Besides this, I think you're a bit confused about GCD. Writing and using a block does not inherently execute it with GCD; that has to be done manually (strictly speaking, a block is simply a collection of lines of code and does not inherently have anything to do with GCD; GCD simply uses blocks for execution).
NSArray
'senumerateObjectsUsingBlock:
method most likely does not use GCD to enumerate the array (at least the reference gives no insight on this, so please prove me wrong), and if it does, it's not because you're supplying it with a block, but rather because that's how Apple chose to implement it. Most methods taking blocks do not use GCD to execute them.I recommend you read the Grand Central Dispatch (GCD) Reference as well as Cocoa Samurai's A Guide to Blocks and GCD to get greater insight into the specifics of the topic.