我有个聊天应用,里面有个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”。但我希望它能一个接一个地连续发送。
发布于 2016-06-04 12:14:18
NSTimer
实例和一个计数器:@property (非原子,强)文本* timer;@property (非原子,赋值)更新定时器为fired:
然而,你不能让定时器在你的应用程序进入后台后无限期地继续工作(除了一些例外: VoIP,GPS应用程序等)。请参考官方文档Background Execution。
发布于 2016-06-04 12:14:03
使用NSTimer
:Documentation of NSTimer
在.h
文件中声明NSTimer
的属性:
@property (retain,nonatomic) NSTimer *myTimer;
- (void)changeSwitch:(id)sender
{
if([sender isOn]){
myTimer = [NSTimer scheduledTimerWithTimeInterval: 4 target: self
selector: @selector(AddMessage:) userInfo: nil repeats: YES];
} else{
[self.timer invalidate];
}
}
每隔4秒,定时器将调用以下函数:
-(void) AddMessage:(NSTimer*) timer
{
//Add Message
}
发布于 2016-06-04 12:17:17
//Nstimer *timer in .h
在UISwitch方法中,编写如下所示
- (void)changeSwitch:(id)sender{
if([sender isOn]){
timer=[NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(targetMethod)
userInfo:nil
repeats:NO];
}
else
{
[timer invalidate];
}
}
像这样的targetMethod
-(void)targetMethod
{
[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];
}
https://stackoverflow.com/questions/37626165
复制相似问题