scheduledTimerWithTimeInterval vs performselector with delay with iOS 5.0

Paras Gandhi picture Paras Gandhi · Nov 14, 2011 · Viewed 13.1k times · Source

i am doing function call with scheduledTimerWithTimeInterval. i am just checking that xml parsing is completed or not for particular web services and invalidating timer in didEndElement method after getting successful response.

timerForStopWebService = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(stopWS) userInfo:nil repeats:NO];

now i am facing problem with iOS 5.0 and its working fine in other iOS versions. in iOS 5.0, a function stopWS call anytime even if i am invalidating it. let me know if you have solution for that.

and now i am implementing performselector with delay and set boolean variables in stopWS to identify that parsing is completed or not. i just want to know that is there any major difference between this? and does this solution works for my problem?

if other way exists, please suggest me, thanks.

Answer

Abhinit picture Abhinit · Nov 23, 2011

Here are your differences

performSelectorWithObjectAfterDelay

  • as the name suggests performs a selector after a specified number of seconds. ONCE.

  • The care that you need to take here is that you need to cancel any previous perform requests before the object that the selector is being performed on is released. For that use the cancelPerformSelector method.

scheduledTimerWithTimeInterval

  • this method gives you the ability to call a selector after a specified duration too but it also has a parameter [repeats:] that lets you call the same selector REPEATEDLY

  • You can also pass in invocations to call selectors, which are specially helpful when your selector needs a lot of arguments.

  • You need to invalidate the timer when its no longer needed. This should do the trick

    [myTimer invalidate]; myTimer = nil;

Also this is the most definitive thread on NSTimer, please have a look at it. How do I use NSTimer?