喔盡量分成一小節一小節的寫。這樣也難讓大家看的清楚些。我這裡有三種創建線程的方法。代碼如下
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
//當用戶點擊屏幕,執行線程
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self testThread];
}
-(void)testThread
{
//取到當前線程,在這裡就是主線程
NSThread *curThread = [NSThread currentThread];
NSLog(@"curThread = %@",curThread);
// //取到主線程的方法
// NSThread *mainThread = [NSThread mainThread];
// NSLog(@"mainThread = %@",mainThread);
//
[self createThread1];
}
-(void)createThread1
{
//一個NSThread對象就是一個線程
// 參數1,2 : 指定線程中由參數1調用參數2的方法
// 參數3 : 給參數2指定的方法傳遞實參
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(threadMain:) object:@"線程創建方式1"];
[thread setName:@"我叫二蛋"];
[thread start];
}
-(void)createThread2
{
[NSThread detachNewThreadSelector:@selector(threadMain:) toTarget:self withObject:@"線程創建方式2"];
}
-(void)createThread3
{
[self performSelectorInBackground:@selector(threadMain:) withObject:@"線程創建方式3"];
}
-(void)threadMain:(id)obj
{
for (int i = 0; i<1000; i++) {
NSLog(@"i = %d,obj = %@,thread = %@",i,obj,[NSThread currentThread]);
}
}
當然大家還是需要多用,就像吃飯,吃的多了還能挑刺,繼續下一篇,今天晚上3更。哈哈