1

I have a static method that creates a NSTimer and runs it in the background thread, like so:

+ (void) callInBackgroundThread {
    NSTimer *timer = [NSTimer timerWithTimeInterval:0.2
                                            target:self
                                          selector:@selector(callToMainThread)
                                          userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

and then i call the main thread upon completion like so:

+ (void) callToMainThread{
    NSTimer *timer = [NSTimer timerWithTimeInterval:0
                                             target:self
                                           selector:@selector(foo1)
                                           userInfo:nil repeats:NO];
   [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}

While this works i feel that this is quite sketchy and I wonder if there is a better way of doing this. I would appreciate suggestions, please note that the methods where are static.

Any help would be appreciated.

Regards

RicardoDuarte
  • 728
  • 7
  • 23
  • 1
    here is the link about NSTimers and GCD: http://stackoverflow.com/questions/12323531/difference-in-scheduling-nstimer-in-main-thread-and-background-thread – Eugene Gordin May 13 '14 at 22:44
  • @EugeneGordin thanks that post explained it quite nicely, spent a few hours looking for it but didn't see it. – RicardoDuarte May 13 '14 at 22:56

1 Answers1

1

performSelectorOnMainThread:withObject:waitUntilDone: also works for classes!

+ (void) callToMainThread {
   [self performSelectorOnMainThread:@selector(foo1) withObject:nil waitUntilDone:NO];
}
NobodyNada
  • 7,529
  • 6
  • 44
  • 51
  • Thanks for your reply, but this method is not static, it is an instance method see [apple link](https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/classes/nsobject_class/reference/reference.html#//apple_ref/occ/instm/NSObject/performSelectorOnMainThread:withObject:waitUntilDone:) – RicardoDuarte May 13 '14 at 23:05
  • 1
    Classes are actually instances of `NSObject`. See [http://stackoverflow.com/a/5642494/3476191](http://stackoverflow.com/a/5642494/3476191) – NobodyNada May 13 '14 at 23:08