2012-02-01 100 views
0

是否可以在iOS中调用某个函数一定的时间间隔?在iOS中每5秒钟调用一次函数

{ 
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(serverConnect) userInfo:nil repeats:YES]; 
    } 

有没有其他替代方案?

服务器连接功能如下:

-(void)serverConnect{ 

NSMutableURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@MYURL] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15.0]; 

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

if(connection){ 

    NSLog(@"connected"); 
}else{ 
    // 

} 

它引发错误: - [TUTViewController serverConnect:]:无法识别的选择发送到实例0x907ef20

+0

这几乎是做到这一点。全球化'NSTimer',你可以在其他地方无效,如果你需要的话。 – MobileOverlord 2012-02-01 01:52:28

+0

这就是你如何做一个重复计时器,但它会每隔100秒运行一次。这是你真正想要的吗? – jsd 2012-02-01 01:52:28

+0

我改变了时间间隔并添加了被调用的函数。 – 2012-02-01 02:01:04

回答

2

的误差指示的问题。它显示'serverConnect:' - 末尾的冒号表示有一个参数。你的serverConnect没有参数...因此,这个问题。它需要看起来像:

- (void)serverConnect:(NSTimer*)theTimer { 
    ... 
} 
+0

但我不使用该计时器,只是调用该函数。我的想法是每5秒连接一次服务器。没什么。它仍然适用? – 2012-02-01 02:21:54

+0

函数必须采用参数,无论您是否使用它。 NSTimer文档可以证实这一点。 – 2012-02-01 05:37:04