最后,我通过以下 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