NSThread 的 Target

NSThread 的实例化方法中的 target 指的是开启线程后,在线程中执行 哪一个对象@selector 方法;

  • 通过指定不同的 target 会在后台线程执行该对象的 @selector 方法
  • 提示:不要看见 target 就写 self

先准备一个准备对象:

@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@end

@implementation Person

+ (instancetype)personWithDict:(NSDictionary *)dict {
    id obj = [[self alloc] init];

    [obj setValuesForKeysWithDictionary:dict];

    return obj;
}

- (void)longOperation:(id)obj {
    NSLog(@"%@ - %@ - %@", [NSThread currentThread], self.name, obj);
}

@end

三种线程调度方法:

//定义属性
@property (nonatomic, strong) Person *person;

//懒加载
- (Person *)person {
    if (_person == nil) {
        _person = [Person personWithDict:@{@"name": @"zhangsan"}];
    }
    return _person;
}
  • alloc / init
NSThread *thread = [[NSThread alloc] initWithTarget:self.person selector:@selector(longOperation:) object:@"THREAD"];

[thread start];
  • detach
[NSThread detachNewThreadSelector:@selector(longOperation:) toTarget:self.person withObject:@"DETACH"];
  • 分类方法
[self.person performSelectorInBackground:@selector(longOperation:) withObject:@"PERFORM"];

results matching ""

    No results matching ""