2012-06-01 54 views
2

嗨我在我的应用程序中使用SQllite。我希望在数据库进程开始和结束时显示活动指示器。活动指示器不能正常工作

这里是我的代码:

[activityIndicator startAnimating]; 
// DB Open 

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

当我尝试这一点,它不能正常工作。 sqllite代码是否阻塞指示符的动画?我在滚动视图中使用活动指示器。

+0

你是从主线程执行此操作吗? – epatel

回答

3

,为什么它不工作的原因很简单:的UI只得到更新当前runloop有后终止。 runloop包含您在单个线程(当前,您的应用程序的主线程)中进行的所有调用。例如,如果你打电话给for (int i=1; i<1000; i++) { label.text = i }(粗糙的伪代码),你的标签不会显示1000个文本改变,它只会显示最终值。

这是通过UIKit完成的,因此界面可以平滑无锯齿。

如果你真的真的想用同一个方法在UI上执行多个更新,你必须在后台线程中执行你的计算。 其他答案提到使用延迟呼叫(0.1秒),但这是无用的,并且如果你重复地调用这个,例如一百次,它会产生巨大的滞后。正确的解决方法是这样的:

- (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]; 
} 

如果你想惹的技术的东西,看看一个线程编程指南或NSRunloop参考。

+0

Thanx Cyrille很好的解释.... – Swapnil

+0

请注意,根据您的SQLite线程设置(请参阅http ://www.sqlite.org/threadsafe.html)使用此特定解决方案(performSelectorInBackground :)解决此问题可能不是一个好主意。 –

0

尝试在延迟几秒后调用处理部分。

[activityIndicator startAnimating]; 

//在不同的方法(DB打开)

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

的延迟,将工作之后,调用此部分。

+1

Thanx Mitesh ...它的工作! – Swapnil

+0

你不能阻塞主线程,考虑处理后台线程中的所有数据库相关的东西 – beefon

4

试试下面的代码:

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

创建DB工艺方法

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

} 
+0

谢谢!!!!这对我工作 – user1489709