How to lazy / asynchronously load various elements (data in shortcuts) in a view?

I have a ViewController with various shortcuts. Each of these labels is dynamically populated at runtime based on different regular expression parsing logic executed on the html page. The problem is that each regular expression takes 2-3 seconds, and I have 8 such labels, so I have to wait somewhere around 20-25 seconds before the presentation appears!

This is a very bad user interface. I want this to make it less painful for the user and therefore want to load each label independently when and when they receive data after processing the regular expression, and do not wait until all 8 marks have finished searching for their regular expressions.

Anyway, can this be achieved in ios 5?

+3
source share
3 answers
  • Create a separate function that calculates the values ​​you need.
    (You probably already have this to ensure code readability / maintainability.)
  • Run this thread in the background thread.
  • When you are ready to actually set the text, make sure you do this in the main thread:

Here is an example:

- (void)calculateLabelText {
    NSString *label1Text = // However you calculate this...
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        self.label1.text = label1Text;
    });

    NSString *label2Text = // However you calculate this...
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        self.label2.text = label2Text;
    });
}

In viewDidLoad add this:

[self performSelectorInBackground:@selector(calculateLabelText) withObject:nil];
+2
source

Grand Central Dispatch (GCD). .. . , , , dispatch_async() , , - , :)

// ( ).

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);

{

dispatch_async(queue, ^{
     // your regex here for one 

     // execute back in the main thread since UIKit only operates in the main thread.

    dispatch_async(dispatch_get_main_queue(), ^{
        [myLabel setText:<result of operations>];
    });
}); 

}

+1

, , . , - . , sqlite ( , db) .

0
source

All Articles