【发布时间】:2023-08-12 18:07:01
【问题描述】:
我有一个带有 uiswitch 的聊天应用程序。如果开关按钮打开,我希望应用程序每 3 秒连续发送一次“hi”,即使应用程序处于后台模式。我知道我可以使用 NSTimer,但我真的不知道如何在这段代码中实现它(这是我第一次开发 iOS 应用程序)。请帮我解决这个问题。
我的代码是:
// Allocate, initialize, and add the automatic button.
_AutomaticSend = [[UISwitch alloc] initWithFrame:CGRectMake([self width] - 50.0, textAreaY + Center(160.0, textAreaHeight), 50.0, 50.0)];
[_AutomaticSend addTarget:self action:@selector(changeSwitch:) forControlEvents:UIControlEventValueChanged];
和
// Switch action
//NSUInteger counter = 0;
- (void)changeSwitch:(id)sender{
if([sender isOn]){
for (int a=1; a<=300; a++)
{
//[self performSelector:@selector(changeSwitch:) withObject:_textField afterDelay:70.0];
[sender setOn:YES animated:YES];
[_textField setText:@"hi"];
NSString * text = [_textField text];
// Update status.
[[TSNAppContext singleton] updateStatus:text];
// Add the status to the bubble.
[self appendLocalPeerTableViewCellWithMessage:text];
}
// NSLog(@"Switch is ON");
} else{
NSLog(@"Switch is OFF");
}
}
现在,在所有 300 个“hi”都准备好显示后,应用程序正在显示所有“hi”。但我希望它一个接一个地连续发送。
【问题讨论】:
-
每 3 秒调用一次函数,而不是每 3 秒收到消息
-
有什么方法可以每 3 秒自动调用一次我的函数吗?
-
使用
NStimer每 4 秒调用一次您的方法
标签: ios objective-c uiswitch