开发者

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
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜