1.我自定义了一个类,叫RunloopThread
2.我在RunloopThread里创建了一个线程,然后在线程里起了一个runloop
3.往runloop里添加了一个timer
问题 : 我发现无法释放这个类
代码如下:
#import "RunloopThread.h" @interface RunloopThread () @property (nonatomic, strong)NSTimer *archiveringTimer; @end static NSThread *thread; static NSPort *port; @implementation RunloopThread -(void)dealloc { } -(instancetype)init { self = [super init]; if (self) { } return self; } -(void)start{ [self _d_cleaningInBackgroudSchedule]; } -(void)closeSelf{ NSRunLoop *loop = [NSRunLoop currentRunLoop]; [loop removePort:port forMode:NSDefaultRunLoopMode]; [_archiveringTimer invalidate]; _archiveringTimer = nil; [NSThread exit]; thread = nil; CFRunLoopStop(CFRunLoopGetCurrent()); } +(NSThread *)workThread { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ if (!thread) { thread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint) object:nil]; [thread start]; } }); return thread; } +(void)networkRequestThreadEntryPoint{ @autoreleasepool { NSThread *thread = [NSThread currentThread]; thread.name = @"com.thread.archive"; NSRunLoop *runloop = [NSRunLoop currentRunLoop]; port = [NSMachPort port]; [runloop addPort:port forMode:NSDefaultRunLoopMode]; CFRunLoopRun(); } } -(void)_d_cleaningInBackgroudSchedule { if (!thread) { [self performSelector:@selector(_d_cleaningInBackgroud) onThread:[[self class] workThread] withObject:nil waitUntilDone:NO]; } } -(void)_d_cleaningInBackgroud{ //1. 获取当前线程的runloop NSRunLoop *loop = [NSRunLoop currentRunLoop]; //2.创建timer _archiveringTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(_d_cleaningInBackgroud2) userInfo:nil repeats:YES]; //3. 将NSTimer添加到runloop [loop addTimer:_archiveringTimer forMode:NSDefaultRunLoopMode]; } static int ii = 0; -(void)_d_cleaningInBackgroud2{ BOOL y = [NSThread isMainThread]; if (!y) { NSLog(@"我在异步处理点事情"); ii ++; if ( ii == 5) { [self closeSelf]; } } } @end
请问各位大神,我的问题出在哪里,要怎么解决呢?
[NSThread exit]; 去掉就好了
可以看看这个深入理解RunLoop