views:

77

answers:

3

How can I call a static method asynchronously?

+ (void) readDataFromServerAndStoreToDatabase
{
     //do stuff here
     //might take up to 10 seconds
}
+6  A: 

Use an NSThread:

[NSThread detachNewThreadSelector:@selector(readDataFromServerAndStoreToDatabase)
                         toTarget:[MyClass class]
                       withObject:nil];
mipadi
Don't know why this was voted down. It succinctly and quite directly answered the question.
bbum
I agree so + 1.
JeremyP
+3  A: 

You can use this method against the class object. Suppose you have

@interface MyClass:NSObject{
....
}
+ (void) readAndStoreDataToDatabase;
@end

and then do

NSThread*thread=[NSThread detachNewThreadSelector:@selector(readAndStoreDataToDatabase)
                                           target:[MyClass class]
                                       withObject:nil ];

Note that the class object of a class inheriting from NSObject is an NSObject, so you can pass it to these methods. See by yourself by running this program:

#import <Foundation/Foundation.h>

int main(){
    NSAutoreleasePool*pool=[[NSAutoreleasePool alloc] init];
    NSString* foo=@"foo";
    if([foo isKindOfClass:[NSObject class]]){
        NSLog(@"%@",@"YES");
    }else{
        NSLog(@"%@",@"NO");     
    }
    if([[NSString class] isKindOfClass:[NSObject class]]){
        NSLog(@"%@",@"YES");
    }else{
        NSLog(@"%@",@"NO");     
    }
    [pool drain];
}

The point is that, in Objective-C, class methods (which are called static methods in C++) are just standard methods sent to the class object. For more on class objects, see these great blog posts by Hamster and by Cocoa with Love.

Yuji
Correct, but I'd wager that the questioner has no idea how much rope they've just been handed. ;)
bbum
I do, I have done a lot of threading before, I just didn't know it was possible to call a static method through a thread, so the keyword here was [MyClass class]
aryaxt
There's no such thing as a `static` method in Objective-C :) They are `class methods`, and they are sent `dynamically` to the class object. Once you get that, it's perfectly natural that you can do this.
Yuji
+4  A: 

There are several ways to accomplish concurrency in objective-C, depending on the environment you're running in. pthreads, NSThreads, NSOperations, GCD & blocks all have their place. You should read Apple's "Concurrency Programming Guide" for whichever platform you're targeting.

codelark
+1 for mentioning the broad choice of options, and the relevant guide
David Gelhar