iOS NSThread和NSOperation的基本使用詳解
更新時間:2018年01月15日 09:45:58 作者:鍵盤舞者113
下面小編就為大家分享一篇iOS NSThread和NSOperation的基本使用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
NSThread適合簡單的耗時任務的執(zhí)行,它有兩種執(zhí)行方法
- (void)oneClick{
[NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:@"oneClick"];
}
-(void)doSomething:(NSString*) str{
NSLog(@"%@",str);
}
- (void)twoClick{
NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(doSomething:)
object:@"twoClick"];
[myThread start];
}
NSOperation適合需要復雜的線程調度的方法,然后它默認是使用主線程不會創(chuàng)建子線程
- (void)threeClick{
// 1.創(chuàng)建NSInvocationOperation對象
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil];
// 2.調用start方法開始執(zhí)行操作
[op start];
}
- (void)run
{
NSLog(@"------%@", [NSThread currentThread]);
}
- (void)fourClick{
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
// 在主線程
NSLog(@"1------%@", [NSThread currentThread]);
}];
// 添加額外的任務(在子線程執(zhí)行)
[op addExecutionBlock:^{
NSLog(@"2------%@", [NSThread currentThread]);
}];
[op addExecutionBlock:^{
NSLog(@"3------%@", [NSThread currentThread]);
}];
[op addExecutionBlock:^{
NSLog(@"4------%@", [NSThread currentThread]);
}];
[op start];
}
以上這篇iOS NSThread和NSOperation的基本使用詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
iOS中從網(wǎng)絡獲取數(shù)據(jù)的幾種方法的比較
IOS中獲取網(wǎng)絡數(shù)據(jù)一般有三種:1、NSURLCondition(已過時) 2、NSURLSession 3、三方庫AFNetWorking。下面通過本文給大家比較這三種方法的區(qū)別對比2017-11-11
iOS基礎知識之@property 和 Ivar 的區(qū)別
這篇文章主要介紹了iOS基礎知識之@property 和 Ivar 的區(qū)別介紹,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-08-08

