What is the best way to handle intensive data processing in iOS?

Currently, my iOS application generates a certain number of random numbers defined by the user at the same time. My concern is that when a user requests a large number of random numbers, the application will freeze and even work. What is the best solution? Should I share a task among multiple threads? I'm not sure how best to approach this. Thanks in advance!

0
source share
1 answer

One way to do this is to use GCD to split the job and send it to the parallel queue using the send group. Then you can use dispatch_group_notify()to do something with the work when all parallel work units have been completed. This will support your application while doing the work. After sub-units of work are performed, the results are sent back to the main queue (which is the user interface queue) for aggregation.

You should read this too: https://mikeash.com/pyblog/friday-qa-2009-09-25-gcd-practicum.html

Here is a sample code that I worked with very quickly:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    const NSUInteger count = 100;  // Total number of random numbers to generate.
    const NSUInteger workUnitCount = 4;  // Take note: this conveniently divides count evenly.
    const NSUInteger countPerWorkUnit = count / workUnitCount;

    dispatch_group_t numberGroup = dispatch_group_create();
    dispatch_queue_t numberQueue = dispatch_queue_create("numberQueue", DISPATCH_QUEUE_CONCURRENT);

    NSMutableArray *__block results = [NSMutableArray arrayWithCapacity:count];

    for (int i = 0; i < workUnitCount; ++i) {
        dispatch_group_async(numberGroup, numberQueue, ^{
            NSMutableArray *workUnitResults = [NSMutableArray arrayWithCapacity:workUnitCount];
            for (int i = 0; i < countPerWorkUnit; ++i) {
                [workUnitResults addObject:@(arc4random() % 5000)];  // Arbitrary upper limit.
            }

            // The results array should only be accessed from the main queue.
            dispatch_async(dispatch_get_main_queue(), ^{
                [results addObjectsFromArray:workUnitResults];
            });
        });
    }

    dispatch_group_notify(numberGroup, dispatch_get_main_queue(), ^{
        [results enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSLog(@"random result #%@: %@", @(idx), results[idx]);
        }];
    });

    return YES;
}
0
source

All Articles