天天看點

iOS中NSThread線程

#import "NSThreadViewController.h"

@interface NSThreadViewController ()

@end

@implementation NSThreadViewController

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view.

}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

[self threadDemo];
           

}

-(void)threadDemo{

NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(demo:) object:@"ddd"];


// detach 分離 出來一個子線程
[NSThread detachNewThreadSelector:@selector(demo:) toTarget:self withObject:@"tttt"];

[thread start];



//子線程  所有繼承NSObject的都可以使用
[self performSelectorInBackground:@selector(demo:) withObject:@"ddd"];

//在指定線程上進行操作
[self performSelector:@selector(demo:) onThread:[NSThread mainThread] withObject:@"4444" waitUntilDone:NO];
           

}

-(void)demo:(id)obj {

//交替執行線程
for ( int i = 0; i< 2; i++) {

    NSLog(@"%@%@",[NSThread currentThread],obj);

}
           

}

@end

繼續閱讀