多线程下的performSelector和NSThread的使用

多线程下的performSelector和NSThread的使用

NSThread的多线程使用:

我们可以使用这两种方法来使用线程中的问题

- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument

+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument

第一个是实例方法,传统方法创建一个线程,这个方法必须要在调用了[thread start]的时候才可以运行。

第二个是类方法,创建了之后,会立即调用的。

1、[NSThread detachNewThreadSelector:@selector(selector) toTarget:self withObject:nil];
2、NSThread* myThread = [[NSThread alloc] initWithTarget:self
                                        selector:@selector(selector)
                                        object:nil];
[myThread start];


performSelector来调用多线程:

我们可以使用这两种方法来使用线程中的问题

[self performSelector:@selector(selector) onThread:[NSThread mainThread] withObject:nil waitUntilDone:YES];

[self performSelectorInBackground:@selector(selector) withObject:nil];

第一个为可以指定调用线程的方法。

第二个为可以指定在后台调用事件,线程系统分配的方法。

    [self performSelector:@selector(performSelectorMethods) onThread:[NSThread mainThread] withObject:nil waitUntilDone:YES];
    
    [self performSelectorInBackground:@selector(performselectorINbackgroud) withObject:nil];

下面是使用以上方法的范例:

@implementation NSThreadUSE

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    使用传统方法创建一个线程。这个方法必须要在调用了[thread start]的时候才可以运行
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(initWithTargetMethods) object:nil];
    [thread start];
    
//    使用类方法来调用线程,这个方式会立即调用并执行线程
    [NSThread detachNewThreadSelector:@selector(detachNewThreadMethods) toTarget:self withObject:nil];
    
//    使用performSelector的方法来调用函数,并且设置调用方法的线程
    [self performSelector:@selector(performSelectorMethods) onThread:[NSThread mainThread] withObject:nil waitUntilDone:YES];
    
//    使用performSelectorInBackground这个方法来被调用函数,这个函数是在后台调用的
    [self performSelectorInBackground:@selector(performselectorINbackgroud) withObject:nil];
}

#pragma mark NSThread Methods
-(void) initWithTargetMethods{
    NSLog(@"initWithTargetMethods is ---------------%@", [NSThread currentThread]);
}

-(void) detachNewThreadMethods{
    NSLog(@"detachNewThreadMethods is ---------------%@", [NSThread currentThread]);
}

-(void) performSelectorMethods{
    NSLog(@"performSelectorMethods is ---------------%@", [NSThread currentThread]);
}

-(void) performselectorINbackgroud{
    NSLog(@"performselectorINbackgroud is ---------------%@", [NSThread currentThread]);
}

@end




原文地址:https://www.cnblogs.com/AbeDay/p/5026950.html