如何防止方法一直被调用

时间:2014-02-09 22:59:22

标签: ios objective-c xml xcode delay

-(void) parseXML
{

       [self performSelector:@selector(parseXML) withObject:self afterDelay:55.0 ];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://apikeygoeshere.com/data.xml"]];


    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    NSString *xmlString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];

    NSDictionary *xml = [NSDictionary dictionaryWithXMLString:xmlString];

    NSMutableArray *items = [xml objectForKey:@"TeamLeagueStanding"];

    NSMutableArray *newTeamObjectArray = [[NSMutableArray alloc] init];

    for (NSDictionary *dict in items) {
        TeamObject *myTeams = [TeamObject teamFromXMLDictionary:dict];
        [newTeamObjectArray addObject:myTeams];
    }

    NSNull *nullValue = [NSNull null];
    NSNull *nullValue2 = [NSNull null];

    [newTeamObjectArray insertObject:nullValue atIndex:0];
    [newTeamObjectArray insertObject:nullValue2 atIndex:1];

    NSLog(@"standingsdataaaaa %@", newTeamObjectArray);

 }  

我想在我的故事板上添加一个解开按钮,以便用户可以随时刷新数据,但我不能让他每小时多次执行此操作,

任何人都可以帮助我吗?谢谢。

2 个答案:

答案 0 :(得分:2)

只需在操作方法中或您调用以获取XML的任何位置 setEnabled:NO并设置一个NSTimer来点燃一个从现在起3600秒的日期。 当它触发时,setEnabled:YES

为计数器创建一个可视指示器可能会很好。

答案 1 :(得分:1)

编辑:为了说明你仍然希望每按55秒运行parseXML方法,无论是否按下按钮,我都会通过按下按钮触发的IBAction方法中的条件来改变我的答案而不是将条件放在parseXML中:

将NSTimer声明为类变量。例如,在@synthesize之后直接位于.m的顶部,声明NSTimer:

NSTimer *parseTimer;

然后在按下按钮触发的IBAction方法中,如果计时器为parseXML,则只调用nil;如果它实际上是nil并且parseXML方法将要运行,则启动计时器,使其不再运行一小时:

- (IBAction)buttonPressed:(sender)id {
    // If the parseTimer is active, do call parseXML.
    // (And perhaps fire an alert here)
    if (parseTimer != nil) return;

    // Otherwise initialize the timer so that it calls the the method which
    // will deactivate it in 60*60 seconds, i.e. one hour
    parseTimer = [NSTimer scheduledTimerWithTimeInterval:60*60 target:self selector:@selector(reactivateButton) userInfo:nil repeats:YES];

    [self parseXML];
}

deactivateParseTimer方法应停用计时器并将其设置为nil,以便parseXML可以再次运行:

- (void)deactivateParseTimer {
    [parseTimer invalidate];
    parseTimer = nil;
}