Memory leaks when generating dispatch source timer events - iphone

We are using dispatch queues to generate timer events. Following is the code which does the task:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
if (!timer) return self;
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), interval * NSEC_PER_SEC, 5 * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer,
^{
//Some work…
});
This works very well except that when we run the profiler, we see a lot of memory leaks from these methods:
dispatch_source_create
dispatch_source_set_timer
dispatch_source_set_event_handler
We had made sure that timer is released using dispatch_release() method.
Can someone please let us know if there is any mistake we are doing in the code above? And also if you can point out any example of timer event generation, it would be helpful.

dispatch_source_set_timer(3) Mac OS X Manual Page
All timers will repeat indefinitely until
dispatch_source_cancel() is called.
How do you call dispatch_source_cancel() and dispatch_release() for the timer?
Dispatch source timer example:
dispatch_source_t timer = dispatch_source_create(
DISPATCH_SOURCE_TYPE_TIMER, 0, 0,
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
dispatch_source_set_timer(timer,
dispatch_time(DISPATCH_TIME_NOW, 1ull * NSEC_PER_SEC),
DISPATCH_TIME_FOREVER, 1ull * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{
NSLog(#"wakeup!");
dispatch_source_cancel(timer);
});
dispatch_source_set_cancel_handler(timer, ^{
NSLog(#"canceled");
dispatch_release(timer);
});
dispatch_resume(timer);

Related

Delay part of iPhone method

I have a method that takes several params, I need to delay a portion of that method. I DO NOT want to split it into several methods and use [self performSelectorAfterDelay] because the delay requires params already in that method. I need something like the following
-(void)someMethod{
.....
delay {
more code but not a separate self method
}
... finish method
}
The dispatch_after function seems to line up with what you need:
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
// this code is going to be executed, on the main queue (or thread) after 2.0 seconds.
});
Of course, the time is configureable, and it's a bit confusing to read at first, but once you get used to how blocks work in conjunction with objective-c code, you should be good to go.
One word of caution:
NEVER, NEVER, NEVER! Block the main thread of an iPhone app using sleep(). Just don't do it!
Looks like an overkill.
-(void)someMethod{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSLog(#"Start code");
dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
dispatch_sync(backgroundQueue, ^{
sleep(5);
// delayed code
NSLog(#"Delayed code");
});
dispatch_sync(backgroundQueue, ^{
// finishing code
NSLog(#"Finishing code");
});
});
}
backgroundQueue might be user at external dispatch call. It looks really bad though :)

How to call method with delay and in background thread

I have a method what I want to call after -viewDidLoad and in background thread. Is there way to combine this two methods:
[self performSelector:(SEL) withObject:(id) afterDelay:(NSTimeInterval)]
and
[self performSelectorInBackground:(SEL) withObject:(id)]?
Grand Central Dispatch has dispatch_after() which will execute a block after a specified time on a specified queue. If you create a background queue, you will have the functionality you desire.
dispatch_queue_t myBackgroundQ = dispatch_queue_create("com.romanHouse.backgroundDelay", NULL);
// Could also get a global queue; in this case, don't release it below.
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC);
dispatch_after(delay, myBackgroundQ, ^(void){
[self delayedMethodWithObject:someObject];
});
dispatch_release(myBackgroundQ);
Try the following:
// Run in the background, on the default priority queue
dispatch_async( dispatch_get_global_queue(0, 0), ^{
[self performSelector:(SEL) withObject:(id) afterDelay:(NSTimeInterval)]
});
Code not tested
Be aware that your selector/method must not use UIKit (so don't update the UI) or access UIKit properties (like frame) so your selector may need to kick off work back to the main thread. e.g.
(id)SomeMethod:UsingParams: {
// Do some work but the results
// Run in the background, on the main queue
dispatch_async(dispatch_get_main_queue(), ^{
// Do something UIKit related
});
}
[self performSelector:(SEL) withObject:(id) afterDelay:(NSTimeInterval)]
Performs a selector on the thread that it is being called. So when you call it from a background thread it will run there...
You can do that per example:
dispatch_time_t delay = dispatch_time( DISPATCH_TIME_NOW, <delay in seconds> * NSEC_PER_SEC );
dispatch_after( delay, dispatch_get_main_queue(), ^{
[self performSelectorInBackground: <sel> withObject: <obj>]
});
Somehow a mixed solution. It would be better to stick with a full GCD approach tho.

GCD: How to change timer fire interval

This may sound a newbie question anyway, I'm very new to GCD
I've following code :
int interval = 2;
int leeway = 0;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
if (timer) {
dispatch_source_set_timer(timer, dispatch_walltime(DISPATCH_TIME_NOW, NSEC_PER_SEC * interval), interval * NSEC_PER_SEC, leeway);
dispatch_source_set_event_handler(timer, ^{
[self someMethod];
});
dispatch_resume(timer);
}
Where someMethod is :
- (void)someMethod
{
NSLog(#"Thread 1");
}
How do I change the timer's fire interval property in someMethod ?
Got the answer on my own, calling dispatch_source_set_timer with new interval value is enough

How can I trigger a method every 10 seconds without using NSTimer?

I would like to call a method every 10 seconds, but I want to use something other than NSTimer. What could I use to do this?
I know you said you didn't want to use timers, but just to make sure you know how simple it would be with a timer...
[NSTimer scheduledTimerWithTimeInterval:10.0
target:self
selector:#selector(someMethod)
userInfo:nil
repeats:YES];
If you dont want to use the timer, you can use GCD which internally will make use of NSOperationQueue, nevertheless will work in all cases. For eg: i had a class which was inherited from NSOperation so the above methods didn't work so i had go go with GCD:
double delayInSeconds = 3.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_after(popTime, queue, ^{
[self methodYouWantToCall];
});
The above code calls the method methodYouWantToCall after every three seconds.
You can create a loop with performSelector:withObject:afterDelay: setting afterDelay to 10.0.
I don't recommend this though, use an NSTimer.
- (void)callMeEvery10Seconds
{
[self performSelector:#selector(callMeEvery10Seconds)
withObject:nil
afterDelay:10.0];
// ... code comes here ...
}
If you are not using Cocos2D, you have to use a NSTimer to do this....
If you are using Cocos2D, use the schedule method
here's a link below that shows both :
How can I create a count down timer for cocos2d?
The easiest way to do so is:
- (void)scheduleLoopInSeconds:(NSTimeInterval)delayInSeconds
{
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_after(popTime, queue, ^{
[self callWhatEverMethodYouWant];
[self shceduleLoopcaInSeconds:delayInSeconds];//set next iteration
});
}
// now whenever you like call this, and it will be triggering "callWhatEverMethodYouWant" every 10 secs.
[self shceduleLoopcaInSeconds:10.0];

suspending dispatch timers from main_queue when it was created on another one

Can you suspend a GCD timer from a queue besides the one it's schedule to run on?
I have a timer, created on the global_queue with low priority and when it fires, I manipulate some UI work via the main_queue. For some states in the UI, I have to suspend the timer. Do I have to switch from the main_queue back to the low priority queue to perform the suspend?
dispatch_queue_t lowPriQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
myTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, lowPriQ);
dispatch_source_set_timer(myTimer,
startTime, // now
interval, // 15 seconds
2000ull);
// configure the event handler
dispatch_source_set_event_handler(myTimer, ^{
NSLog(#"Timer fired");
// UI Work
dispatch_async(dispatch_get_main_queue(), ^ {
[self doSomeButtonEnableDisable]
});
});
dispatch_resume(myTimer); // start the timer
- (void)doSomeButtonEnableDisable
{
if (someParticularState) {
// Turn off the timer
// Should I suspend the timer on the low priority global queue
// or is it valid to suspend on the main queue?
dispatch_queue_t lowPriQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
dispatch_async(lowPriQ(), ^ {
dispatch_suspend(myTimer);
});
}
}
Yes, it's valid to suspend a dispatch object from any queue. If a block is currently running when dispatch_suspend() is called, that block will complete execution and subsequent scheduled blocks will be prevented from executing.