您的位置:首页 > 其它

多线程(二)NSThread

2016-03-22 23:39 323 查看
一、NSThread优缺点
优点:NSThread是最轻量级的
缺点:需要自己管理线程的生命周期,线程同步。线程同步对数据的加锁会有一定的系统开销

二、NSThread的使用

创建线程:

+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullableid)argument;
- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullableid)argument; //argument:传输给target的唯一参数,也可以是nil

直接创建线程,并开始执行线程

[NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:nil];

先创建线程对象,然后再运行线程操作,在运行线程操作前可以设置线程的优先级等线程信息

NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(doSomething:)
object:nil];
[myThread start];

不显式创建线程的方法,Swift中去掉了这个方法,苹果认为 performSelector: 不安全,,,,,

NSObject *obj;
[obj performSelectorInBackground:@selector(doSomething) withObject:nil];

例子:
- (void)viewDidLoad {
[super viewDidLoad];
// [NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:kURL];

NSURL *url = [NSURL URLWithString:@"http://h.hiphotos.baidu.com/image/pic/item/5366d0160924ab1828b7c95336fae6cd7b890b34.jpg"];

NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(downloadImage:) object:url];

[thread start];

}

- (void)downloadImage:(NSString *)url {

NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];

UIImage *image = [[UIImage alloc]initWithData:data];

if(image == nil){

}else{

[self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];

}

}

- (void)updateUI:(UIImage *)image {

self.iconView.image = image;
}

更新其他线程

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait

常用属性

//取消线程

- (void)cancel;

//启动线程

- (void)start;

//判断某个线程的状态的属性

@property (readonly, getter=isExecuting) BOOL executing;

@property (readonly, getter=isFinished) BOOL finished;

@property (readonly, getter=isCancelled) BOOL cancelled;

//设置和获取线程名字

-(void)setName:(NSString *)n;

-(NSString *)name;

//获取当前线程信息

+ (NSThread *)currentThread;

//获取主线程信息

+ (NSThread *)mainThread;

//使当前线程暂停一段时间,或者暂停到某个时刻

+ (void)sleepForTimeInterval:(NSTimeInterval)time;
+ (void)sleepUntilDate:(NSDate *)date;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: