如何异步调用Objective-c静态方法?

时间:2010-09-29 02:29:48

标签: objective-c asynchronous static-methods

如何异步调用静态方法?

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

3 个答案:

答案 0 :(得分:16)

使用NSThread

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

答案 1 :(得分:6)

根据您正在运行的环境,有几种方法可以在Objective-C中实现并发.pthreads,NSThreads,NSOperations,GCD&街区都有自己的位置。您应该阅读Apple的“并发编程指南”,了解您所针对的任何平台。

答案 2 :(得分:3)

您可以对类对象使用this method。假设你有

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

然后再做

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

请注意,继承自NSObject的类的类对象是NSObject,因此您可以将其传递给这些方法。通过运行此程序自己查看:

#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];
}

关键是,在Objective-C中,类方法(在C ++中称为静态方法)只是发送给类对象的标准方法。有关课堂对象的更多信息,请参阅HamsterCocoa with Love上的这些精彩博文。

相关问题