#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
@interface myThread : NSThread
-(instancetype) init;
-(instancetype) initWithTarget:(id)target selector:(SEL)selector object:(id)argument;
-(void)main;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
{
NSThread* T;
myThread* myT1;
myThread* myT2;
}
- (void)viewDidLoad {
[super viewDidLoad];
//注意点1:initWithTarget用的sel最多有一个参数,可以没有,有两个能编译,但运行报错。
T = [[NSThread alloc]initWithTarget:self selector:@selector(FunOneParam:) object:@"Hello"];
//[T start];
myT1 = [[myThread alloc] init];
//注意点2:默认创建不启动
//[myT1 start];
//注意点3:即使创建的时候指定了sel,如果有main的话,也不执行sel
myT2 = [[myThread alloc] initWithTarget:self selector:@selector(FunOneParam:) object:@"World"];
[myT2 start];
//注意点4:performSelector这个方法给自定义线程不能执行,除非打开NSRunLoop
[self performSelector:@selector(FunOneParam:) onThread:myT2 withObject:@"1111" waitUntilDone:NO];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)FunNonParam
{
NSLog(@"Non param!");
}
-(void)FunOneParam:(NSString*) Aparam
{
NSLog(@"One param,%@",Aparam);
}
-(void)FunTwoParam:(NSString*) Aparam1
SecParam:(NSString*) AParam2
{
NSLog(@"Two Parms, %@;%@", Aparam1, AParam2);
}
@end
@implementation myThread
{
NSInteger _index;
}
-(instancetype)init
{
if (self = [super init]) {
_index =5;
}
return self;
}
-(instancetype)initWithTarget:(id)target selector:(SEL)selector object:(id)argument
{
_index = 5;
return [super initWithTarget:target selector:selector object:argument];
}
-(void)main
{
while (![self isCancelled]) {
[NSThread sleepForTimeInterval:1];
NSLog(@"%ld",_index);
_index++;
}
}
@end