IOS 다 중 스 레 드 프로 그래 밍 NSThread 사용 방법
NSThread 는 다 중 스 레 드 의 하나 로 두 가지 방법 으로 하위 스 레 드 를 만 듭 니 다.
(1)장점:NSThread 가 GCD,NSOperation 보다 경량급
(2)단점:라인 의 생명주기,라인 동기 화 를 스스로 관리 해 야 한다.스 레 드 동기 화 데이터 에 대한 잠 금 은 일정한 시스템 비용 이 들 것 이다.
첫 번 째 는 숨 기 고 만 드 는 것 입 니 다.다음 과 같은 몇 가지 방법 이 있 습 니 다.
(1)직렬:-(id)performSelector:(SEL)aSelector withObject:(id)object;
(2)배경 실행,병렬 에 많이 사용:-(void)performSelector InBackground:(SEL)aSelector with Object:(nullable id)arg;
(3)실행 지연:-(void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay;
(4)주 스 레 드 로 돌아 가 실행:-(void)performSelectorOnMainThread:(SEL)aSelector with Object:(nullable id)arg wait 완료 할 때 까지:(BOOL)wait;
주의:
(1)방법"+(void)cancelPrevious PerformRequests With Target:(id)aTarget selector:(SEL)aSelector 객체:(nullable id)anArgument; ",또는"+(void)cancelPrevious PerformRequests With Target:(id)aTarget"이 실행 을 중지 합 니 다.
예시:
//하위 스 레 드 만 들 기-암시 적 방법
// -
[self performSelector:@selector(showCount:) withObject:@(11)];
[self performSelector:@selector(showCount:) withObject:@(12)];
[self performSelector:@selector(showCount:) withObject:@(23)];
// - ( )
[self performSelectorInBackground:@selector(showCount:) withObject:@(41)];
[self performSelectorInBackground:@selector(showCount:) withObject:@(42)];
//
[self performSelectorOnMainThread:@selector(showCount:) withObject:@(51) waitUntilDone:YES];
//
[self performSelector:@selector(showCount:) withObject:@(61) afterDelay:5.0];
//
[NSObject cancelPreviousPerformRequestsWithTarget:self];
두 번 째 는 생 성 을 표시 하 는 것 입 니 다.방식 은 다음 과 같 습 니 다.
- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullable id)argument;
주의:(1)방법 을 통 해"-(void)start;"실행 시작 하기;
(2)방법 을 통 해"-(void)cancel;"실행 정지;
예시:
//하위 스 레 드 만 들 기-표시 방법
self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(showCount:) object:@(61)];
self.thread.name = @" ";
[self.thread start];
[self.thread cancel];
코드 예제
- (void)showCount:(NSNumber *)number
{
NSInteger count = arc4random() % 1000;
count = 1000;
for (int i = 0; i < count; i++)
{
NSLog(@" %@ i = %@", number, @(i));
// n
[NSThread sleepForTimeInterval:0.2];
//
// BOOL isStop = [self.thread isCancelled];
// if (isStop)
// {
// NSLog(@"2 ");
// break;
// }
if (isCancelThread)
{
NSLog(@"2 ");
break;
}
}
}
bool isCancelThread = NO;
- (void)stopClick
{
[NSObject cancelPreviousPerformRequestsWithTarget:self];
if (self.thread)
{
BOOL isExecuting = [self.thread isExecuting];
if (isExecuting)
{
NSLog(@"1 ");
// [self.thread cancel];
isCancelThread = YES;
}
}
}
- (void)downloadImage:(NSString *)imageUrl
{
NSURL *url = [NSURL URLWithString:imageUrl];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
UIImage *image = [[UIImage alloc] initWithData:data];
if (image == nil)
{
}
else
{
// [self performSelectorOnMainThread:@selector(updateImage:) withObject:image waitUntilDone:YES];
[self performSelectorInBackground:@selector(updateImage:) withObject:image];
}
// NSURL *url = [NSURL URLWithString:imageUrl];
// NSURLRequest *request = [NSURLRequest requestWithURL:url];
// NSURLSession *session = [NSURLSession sharedSession];
// NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
//
// // , 200
// NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
// NSInteger responseStatusCode = [httpResponse statusCode];
// NSLog(@"%ld", responseStatusCode);
//
// UIImage *image = [UIImage imageWithData:data];
//// [self performSelectorOnMainThread:@selector(updateImage:) withObject:image waitUntilDone:YES];
// [self performSelectorInBackground:@selector(updateImage:) withObject:image];
// }];
//
// // resume
// [dataTask resume];
}
- (void)updateImage:(UIImage *)image
{
self.imageview.image = image;
// self.imageview = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, 10.0, (CGRectGetWidth(self.view.bounds) - 10.0 * 2), (CGRectGetWidth(self.view.bounds) - 10.0 * 2))];
// [self.view addSubview:self.imageview];
// self.imageview.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.2];
//
// self.imageview.image = image;
}
NSString *imageUrl = @"http://ww1.sinaimg.cn/crop.0.0.1242.1242.1024/763fb12bjw8empveq3eq8j20yi0yiwhw.jpg";
//
// [self performSelectorInBackground:@selector(downloadImage:) withObject:imageUrl];
[self performSelectorOnMainThread:@selector(downloadImage:) withObject:imageUrl waitUntilDone:YES];
// -
self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(downloadImage:) object:imageUrl];
self.thread.name = @"imageDownload";
[self.thread start];
궁금 한 점 이 있 으 시 면 메 시 지 를 남기 거나 본 사이트 의 커 뮤 니 티 에 가서 토론 을 교류 하 세 요.읽 어 주 셔 서 감사합니다. 도움 이 되 셨 으 면 좋 겠 습 니 다.본 사이트 에 대한 지지 에 감 사 드 립 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
IOS에서 ReplayKit 및 RTC 사용 방법응용된 소리와 아나운서의 소리를 포함한다.이 두 가지 수요를 감안하여 우리는 스크린 공유를 하는 생방송에 필요한 미디어 흐름을 간단하게 분석할 수 있다. 만약 우리가 Audio App과 Audio Mic를 두 개의 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.