Objecttive-C 建立多執行緒
阿新 • • 發佈:2019-02-08
在Objecttive-C裡建立多執行緒一般有兩種方法, 一種是initWithTarget,還有一種是detachNewThreadSelector。
下面是兩個例項,建立多執行緒的例項,支援傳遞引數.
initWithTarget方式// // main.m // initWithTarget // Created by exchen on 5/8/15. // Copyright (c) 2015 exchen. All rights reserved. // #import <Foundation/Foundation.h> @interface classa : NSObject -(void)StartThread:(NSString *)str; @end @implementation classa -(void)StartThread:(NSString *)str { sleep(3); NSLog(str); exit(0); } @end int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... NSLog(@"Hello, World!"); } classa *a = [[classa alloc] init]; NSThread *thread = [[NSThread alloc] initWithTarget:a selector:@selector(StartThread:) object:@"Start"]; [thread start]; sleep(5); return 0; }
detachNewThreadSelector方式
// // main.m // TestThread // // Created by exchen on 5/8/15. // Copyright (c) 2015 exchen. All rights reserved. // #import <Foundation/Foundation.h> @interface classa : NSObject -(void)StartThread:(NSString *)str; @end @implementation classa -(void)StartThread:(NSString *)str { NSLog(@"%@",str); exit(0); } @end int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... NSLog(@"Hello, World!"); classa *a = [[classa alloc] init]; [NSThread detachNewThreadSelector:@selector(StartThread:) toTarget:a withObject:@"Start"]; sleep(5); } return 0; }