Asynchronous vs Synchronous vs Threading in an iPhone App

后端 未结 8 1386
失恋的感觉
失恋的感觉 2021-01-30 05:28

I\'m in the design stage for an app which will utilize a REST web service and sort of have a dilemma in as far as using asynchronous vs synchronous vs threading. Here\'s the sce

相关标签:
8条回答
  • 2021-01-30 06:22

    Just a thought: If you want to use the Unit Testing framework for the iPhone, you may want to have synchronous functionality, as that could make writing the tests easier.

    However, some of your APIs may not work synchronously, so you need to turn them into sync tasks. Provided the code that performs the unit testing runs in its own thread, you can write a wrapper that will wait until the async task has finished.

    To accomplish that, you'd use a semaphore: Your wrapper function starts the async operation and then uses the semaphore to block itself (i.e. puts itself to sleep). The callback that signals the end of the async event releases the semaphore, so that the sleeping wrapper thread can continue and return.

    0 讨论(0)
  • 2021-01-30 06:24

    I would use dispatch_async with synchronous. This way, you have the advantage of no delegates/NSNotifications and it is non-blocking

    - (NSArray *)users {
        if(users == nil) {
            users = do_sync_request();
        }
    
        return users;
    }
    
    // now when calling the users method, do this
    
    - (NSArray *)getUsers {
         dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
               NSArray *users = [self users];
               dispatch_sync(dispatch_get_main_queue(), ^{
                     return users;
               }
         }
    }
    
    0 讨论(0)
提交回复
热议问题