Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 479
aryaxt Avatar asked Sep 29 '10 02:09

aryaxt


3 Answers

Use an NSThread:

[NSThread detachNewThreadSelector:@selector(readDataFromServerAndStoreToDatabase)
                         toTarget:[MyClass class]
                       withObject:nil];
like image 69
mipadi Avatar answered Oct 13 '22 22:10

mipadi


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.

like image 30
codelark Avatar answered Oct 13 '22 23:10

codelark


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.

like image 32
Yuji Avatar answered Oct 14 '22 00:10

Yuji