- (void)addTimer {
NSLog(@"Retain count A is %ld", CFGetRetainCount((__bridge CFTypeRef)self));
//timerWithTimeInterval:该方法创建的定时器对象默认没有被添加到运行循环。要手动添加
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"--------dispatch_get_main_queue-------");
_timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(longConnectToSocket) userInfo:nil repeats:YES];
//只要将定时器对象添加到运行循环,就会自动开启定时器
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
[_timer fire];
});
// _timer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(longConnectToSocket) userInfo:nil repeats:YES];
NSLog(@"Retain count B is %ld", CFGetRetainCount((__bridge CFTypeRef)self));
}
- (void)removeTimer{
// 让定时器失效:一旦定时器失效。则不能再使用,只能重新创建一个新的定时器
[_timer invalidate];
_timer = nil;
}
// 心跳连接
-(void)longConnectToSocket{
NSLog(@" -- 发送心跳包 -- ");
NSDictionary * param = @{@"memberId" : @"101841"};
[self writeDict:param withMsgType:1];
// 根据服务器要求发送固定格式的数据,假设为指令@".",但是一般不会是这么简单的指令
// NSString *longConnect = @".\n";
// NSData *dataStream = [longConnect dataUsingEncoding:NSUTF8StringEncoding];
// [self writeData:dataStream];
}