ios - 一分钟后用 nstimer 重新加载 json 数据变得疯狂

标签 ios json parsing nstimer

我的日志窗口变得疯狂,一分钟后不断重新加载。我最后是否正确使用了 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/

相关文章:

java - 如何解析 Json 对象中具有相同名称的多个 Json 数组

javascript - 具有多个数组的 JSON 对象

parsing - 如何使用 PARSE 从字符串中解析货币值

c# - Enum 的 TryParse 正在工作,但我认为它不应该

c++ - 解析逗号分隔的 std::string

ios - 如何缩小 iOS 中的图像,消除锯齿但不柔和?

ios - kxsmb 文件夹不下载 libs 文件夹 iOS

ios - 为什么 tableView 单元格不是动态的?

java - 通过 json org.json.JSONException : No value for user 获取信息时出现问题

ios - 如何在 iOS 中查找文本段范围