ios - 如何为多个类实例创建多个 NSTimer?

标签 ios

我正在制作一个使用无线通信的 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/

相关文章:

ios - 如何删除所有注释图钉然后添加一个新图钉

ios - SwiftUI - 在低于或等于 iOS 10 的部署目标上出现 “Use of undeclared type xxx”

objective-c - 捕获输出 :didOutputSampleBuffer:fromConnection: image buffer size is always 360x480 even on iPad

ios - 如何从 iOS 中的谷歌地图返回 native 应用程序

ios - 升级到 Xcode 7 后 UIImagePickerControllerMediaURL 上没有文件

iphone - iOS 错误选择器错误

ios - 在 viewWill 和 viewDid 方法中不调用 super 的后果

ios - Rx swift : Does disposed(by: disposeBag) actually work?

ios - 将 FFmpeg 编译为 iOS 8 框架

ios - 带间隙的散点图 -[NSNull doubleValue] : unrecognized selector sent to instance