我的日志窗口变得疯狂,一分钟后不断重新加载。我最后是否正确使用了 NSTimer? performSelectorOnMainThread 是否正确使用?谢谢
-(void)URL
{
dispatch_async(myQueue, ^{
NSString* myURL= @"https://url.json";
NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString:myURL]];
NSLog(@"url: %@", myURL);
if ((!data) || (data==nil))//v1.2
{
NSLog(@"url: loading ERROR");
[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(URL) userInfo:nil repeats:YES];
}else
{
[self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
}
});
}
- (void)fetchedData:(NSData *)responseData {
NSLog=@"fetch";
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSNumber* spot= [json objectForKey:@"amount"];
float spotfloat = [spot floatValue];
timer = [NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(URL) userInfo:nil repeats:YES];
}
最佳答案
将重复设置为 NO 或设置实际的最大计时器。如果您不设置最长时间,则会无限循环。
[NSTimer ScheduledTimerWithTimeInterval:15 target:self 选择器:@selector(URL) userInfo:nil 重复:NO];
- (void)fetchedData:(NSData *)responseData {
NSLog=@"fetch";
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSNumber* spot= [json objectForKey:@"amount"];
float spotfloat = [spot floatValue];
if (timer < 60)
{
timer = [NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(URL) userInfo:nil repeats:YES];
}
else
{
[timer invalidate];
}
}
关于ios - 一分钟后用 nstimer 重新加载 json 数据变得疯狂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24918290/