Swapnil
Swapnil

Reputation: 1878

Activity Indicator not working properly

Hi I am using SQllite in my application. In that I want to show activity indicator during the time of db process starts and ends.

Here is my code:

[activityIndicator startAnimating];
// DB Open

// DB close
// DB process ends
[activityIndicator stopAnimating];

When I try this, Its not working properly. Does sqllite code blocking animation of indicator? I am using activity indicator in scrollview.

Upvotes: 2

Views: 2451

Answers (3)

Cyrille
Cyrille

Reputation: 25144

The explanation as to why it doesn't work is simple: the UI only gets updated after the current runloop has terminated. The runloop encompasses all calls you're making in a single thread (currently, the main thread of your app).

So for example, if you call something like for (int i=1; i<1000; i++) { label.text = i } (in rough pseudo-code), your label won't display 1000 changes of its text, it'll only display the final value.

It's done this way by UIKit so that the interface can be smooth and jag-free.

If you really, really want to perform multiple updates on the UI in the same method, you have to perform your computation in a background thread. Other answers mention the use of a delayed call (0.1 seconds), but this is useless and it generates huge lags if you call this repeatedly, say a hundred times. The correct solution is this:

- (void)doSomethingVeryLong
{
    [spinner startAnimating];
    // or [SVProgressHud showWithMessage:@"Working"];
    [self performSelectorInBackground:@selector(processStuffInBackground)];
}

- (void)processStuffInBackground
{
    for (int i = 0; i < 1e9; i++)
    {
        /* Make huge computations, 
         * wait for a server, 
         * teach a neurasthenic French (no offence, I'm French)
         */
    }
    [self performSelectorOnMainThread:@selector(workDone)];
}

- (void)workDone
{
    [spinner startAnimating];
    // or [SVProgressHud dismiss];
}

If you wanna mess with the technical stuff, take a look a the Thread programming guide or the NSRunloop reference.

Upvotes: 3

Maulik
Maulik

Reputation: 19418

try below code :

[[activityIndicator startAnimating];
[self performSelector:@selector(DB_process) withObject:nil afterDelay:0.1];

create DB process method

- (void)DB_process
{
   // DB close
   // DB process ends
   [activityIndicator stopAnimating];

}

Upvotes: 3

Mitesh Khatri
Mitesh Khatri

Reputation: 3955

Try to call process part after a delay of few second.

[activityIndicator startAnimating];

// call this part after a delay in different method (DB Open)

// DB close
// DB process ends
[activityIndicator stopAnimating];

It will work.

Upvotes: 0

Related Questions