我正在制作一个使用无线通信的 iOS 应用程序。它的一项功能是检查与其连接的外部设备是否有响应。所以我试图做的是为每个连接的设备创建一个“Device”类,然后为每个设备创建一个 NSTimer 来处理超时。我是这样做的:
“设备”类初始化:
NSTimer* communicationChecker;
- (id)initWithAddress: (NSString*) address;
{
self = [super init];
if (self)
{
_address = address;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateStatus:) name:NOTIFICATION_STATUS object:nil];
communicationChecker = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(iAmDead:) userInfo:nil repeats:YES];
self.readyToRoll = true;
}
return self;
}
计时器选择器:
- (IBAction)iAmDead:(NSTimer*)sender
{
self.readyToRoll = false;
NSLog(@"%@ is dead :(", self.address);
}
通知选择器:
-(void)updateStatus:(NSNotification *) notification
{
NSDictionary* userInfo = notification.userInfo;
NSString* deviceAddress = (NSString*)userInfo[PARAM_DEVICE_ADDRESS];
if ([_address isEqualToString:deviceAddress]) {
self.readyToRoll = true;
[communicationChecker invalidate];
communicationChecker = nil;
communicationChecker = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(iAmDead:) userInfo:nil repeats:YES];
}
}
所以我认为这是如何工作的,每次给定设备收到通知时,它都会更改其“readyToRoll”变量并重置计时器。问题是只有一个设备声明它已死亡(当它们都没有报告状态时),并且它是发送最后一条状态报告消息的设备。我真的不知道该怎么做。是什么导致了这种行为?
最佳答案
我通过将 NSTimer 声明从 .m 文件移动到 .h 解决了这个问题。通过将 NSTimer 添加为属性 (@property NSTimer* communicationChecker;),它会为每个设备启动。现在一切都按预期进行。
我认为 NSTimer 之前只启动了一次,并且只是用不同的参数重新启动。现在每个设备都有自己的计时器。
关于ios - 如何为多个类实例创建多个 NSTimer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27422720/