How can I call a static method asynchronously?
+ (void) readDataFromServerAndStoreToDatabase
{
//do stuff here
//might take up to 10 seconds
}
Use an NSThread
:
[NSThread detachNewThreadSelector:@selector(readDataFromServerAndStoreToDatabase)
toTarget:[MyClass class]
withObject:nil];
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With