asynchronous calls to database in ios

Discussion in 'iOS Programming' started by ashwinr87, Oct 3, 2011.

  1. ashwinr87 macrumors member

    Joined:
    Mar 9, 2011
    #1
    I have 4 UITableView's on my iPAD application. I load the data on them using a function loadData ,which is there in all the 4 TableViewController.m files, which makes calls to the database.

    So, I would be doing something like this

    Code:
    [aView loadData];
    [bView loadData];
    [cView loadData];
    [dView loadData];
    Where aView, bView, cView and dView are the view controllers of the UITableView's.

    However, the database calls happen synchronously and hence only after the data is retrieved from the [aView loadData] function, does the [bView loadData] function get called and so on.

    This affects my performance.

    I would like to know if there is a way I can asynchronously make calls to the database/ asynchronously make calls to functions which calls database.

    It would be great if someone could help me out with this.
     
  2. jiminaus macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
  3. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #3
    Use NSOperation to run tasks in background threads. Accumulate your data into an array in the background thread and use performSelectorOnMainThread to send the array to the main thread.

    If these are sqlite dbs you need to open a new db handle from each thread.
     
  4. North Bronson macrumors 6502

    Joined:
    Oct 31, 2007
    Location:
    San José
    #4
    The trouble with these methods is that if the background work needs to pass back multiple objects to the main thread, the background thread has to package those objects up into a dictionary (or custom object) and send that container object back to the main thread (which then has to unpack all of those objects). The block APIs feel like a much smoother approach. Instead of calling something like performSelectorOnMainThread, the background work just passes a block to the operation queue bound to the main thread and this block has all the state that the main thread needs to do its work. If your application is targeting older versions of the OS, you're stuck, but if you have a new application I really feel you can leave these old methods behind.

    I would still recommend just using GCD unless there was some powerful reason why you wanted to stay in the object-oriented world.

    Why are you loading the data for four different table views at the same time? Is there a way you could break up the loading so that it only loaded on-demand as soon as the user explicitly requests the data? Is there a reason you absolutely have to front-load all of these tables? If there is a way to load the data lazily, you will also get a big win in responsiveness.
     

Share This Page