我有一个线程正在递增变量“int count”的值。我想用新的“int count”值更新我的UI,直到我按停止按钮停止增量。我已经设法更新用户界面,但内存占用不断增长。它不会显示为内存泄漏,但它是一个分配问题。每次调用线程中的UI元素时,堆大小都会增加。我可以清楚地看到仪器泄漏分配部分,我有一些分配只有在移动触摸UI元素的窗口时才会被释放。尽管尝试了一切,我仍然无法解决问题。 如果有更好的方法用“int count”新值更新UI元素,请随时通知我。 谢谢objective c cocoa从单独的线程更新gui
我发布了下面的可可项目的链接,如果你想运行仪器或分配来查看问题或查看源代码。这是一个只有几行的小型项目。所有的
-(void) incrementCountGUI:(id)param{ // increment count and update gui
NSAutoreleasePool *pool=[[NSAutoreleasePool alloc]init];// pool just added
count++;
if (count>=100) {// MAKE SURE COUNT DOESN'T GO ABOVE 100
count=0;
}
[sliderDisplayOutlet setIntValue:count];// display value of count in textfield
[sliderOutlet setIntValue:count];// move slider to value of count
[pool release];
}
+(void) updateSliderThread:(id)param{// this thread will call incrementCountGUI method to continuously upgrade UI in the background
NSAutoreleasePool *myThreadPool=[[NSAutoreleasePool alloc]init];
while (shoudStop==NO) {
[ sharedAppInstance performSelectorOnMainThread:@selector(incrementCountGUI:) // update ui in main thread
withObject:nil
waitUntilDone:NO];
usleep(5000);// sleep microsec;
}
[myThreadPool release];
}
- (IBAction)stopCountAction:(id)sender {// START OR STOP counter thread
if ([stopCountButtonOutlet state]==1) { // button depressed=>START
shoudStop=NO;
[NSThread detachNewThreadSelector:@selector(updateSliderThread:) toTarget:[AppController class] withObject:nil];
[stopCountButtonOutlet setTitle: @" STOP" ];
}
if ([stopCountButtonOutlet state]==0){//button depressed=> STOP thread
shoudStop=YES;
[stopCountButtonOutlet setTitle:@" START INCREMENTING COUNT FROM THREAD "];
}
}
- (IBAction)sliderAction:(id)sender { // you can change the value of the variable count manualy.
count=[sliderOutlet intValue];
[sliderDisplayOutlet setIntValue:count];// display value of count
}
为什么要创建一个自动释放池,如果你不会耗尽它? – bryanmac
@bryanmac新线程的标准练习。所有的线程方法都应该有一个autorelease池。你如何知道performSelectorOnMainThread:不会将任何autorelease'd对象添加到当前池中? –
我添加了一个autorelease池到我的方法“incrementCountGui”,但它没有帮助。堆大小不断增加我甚至可以在活动监视器上看到它 –