aryaxt
aryaxt

Reputation: 77626

How can I call an Objective-c static method asynchronously?

How can I call a static method asynchronously?

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

Upvotes: 6

Views: 3325

Answers (3)

Yuji
Yuji

Reputation: 34185

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.

Upvotes: 3

mipadi
mipadi

Reputation: 411012

Use an NSThread:

[NSThread detachNewThreadSelector:@selector(readDataFromServerAndStoreToDatabase)
                         toTarget:[MyClass class]
                       withObject:nil];

Upvotes: 16

codelark
codelark

Reputation: 12334

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.

Upvotes: 6

Related Questions