【问题标题】:Updating the UI control's value in the runtime from background thread.在运行时从后台线程更新 UI 控件的值。
【发布时间】:2013-06-04 06:25:01
【问题描述】:

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

在下面的代码中,我试图在 TexView 控件中显示文本内容。当我将 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;
  }

}

你能帮帮我吗?多谢!!! -梯瓦

【问题讨论】:

    标签: multithreading uitextview main


    【解决方案1】:

    最后我通过以下 URL 的帮助找到了解决方案。 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-24
      • 2018-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多