从后台线程更新运行时中UI控件的值。

时间:2013-06-07 20:47:34

标签: multithreading uitextview main

我知道这听起来很简单。我仍然是iPad应用程序开发的新手。您能否告诉我如何在运行时更新内容。以下代码可能有助于详细了解我的问题。

在下面的代码中,我试图在TexViewcontrol中显示文本内容。当我将for循环形式10更改为100000时,我需要等到所有内容都填满。我需要在循环运行时在屏幕上显示内容。

- (IBAction)RunHelloWorld:(id)sender
 {
    tctView.text = @"tt";

  for(int i=0;i<10;i++)
  {
    NSString *result1 = @"Testing";

    tctView.text = [tctView.text stringByAppendingString:result1];

    tctView.scrollEnabled = YES;
  }

}
你能帮我一下吗?非常感谢!!! -Teva

1 个答案:

答案 0 :(得分:0)

最后,我找到了解决方案,并提供了以下网址的帮助。 http://samplecodebank.blogspot.com/2011/05/nsthread-example_12.html 非常感谢!

这是我的代码。

PCViewController.h文件代码

#import <UIKit/UIKit.h>

 @interface PCViewController : UIViewController
 {
   IBOutlet UITextView *txtView;
 }

 -(void)ReadFile;
 - (void) mainThreadSetText:(NSString*)text;
@end

PCViewController.m文件代码

#import "PCViewController.h"

@interface PCViewController ()

@end

@implementation PCViewController

- (void)viewDidLoad
 {
   [super viewDidLoad];

   [NSThread detachNewThreadSelector:@selector(ReadFile) toTarget:self withObject:nil];

 }

- (void)didReceiveMemoryWarning
  {
     [super didReceiveMemoryWarning];
  }

-(void)ReadFile
{
  // Check whether current thread is externally terminated or not.

   char line[1024];

   FILE *fp = fopen("/Users/Teva/Desktop/File1.txt","r");

   while([[NSThread currentThread] isCancelled] == NO)

   {
     if( fp != NULL )
     {
         while( fgets(line,1024,fp) )
          {
             printf("%s\n",line);

             NSString *result1 = [NSString stringWithCString:line encoding:NSASCIIStringEncoding];

            [self performSelectorOnMainThread:@selector(mainThreadSetText:) withObject:result1 waitUntilDone:YES];

            [NSThread sleepForTimeInterval:1.0];
          }
      }   
    }
  }

  //  Screen processing should be done outside the Thread.
 - (void) mainThreadSetText:(NSString*)text
  {
    txtView.text = [txtView.text stringByAppendingString:text];    
    txtView.scrollEnabled = YES;
  }

 - (void)dealloc
  {
     [txtView release];
     [super dealloc];
   }

 @end