In Cocoa/Objective C, are static class methods thread safe ? I am defining a class to make related custom URL requests, that I would like to call from many different threads. Let’s say I have a class:
@interface URLConnector : NSObject {
}
+(Response *)getData:(NSString *)category;
+(Response *)put:(NSString *)category content:(NSData *)content;
@end
Each method defines an NSMutableURLRequest, calls it, and uses NSRunLoop:runUntilDate: to wait for the response. They also create instances of another class, URLConnectorDelegate to handle the callbacks from the NSMutableRequests, and release them before returning. (note: this code is based on a popular public library for making URL requests)
What I like about this approach is that it keeps all the threads simple and puts all the custom server-related code in one place. The threads can execute URL requests with a single function call.
Can all of my threads use these static functions at once to make simultaneous calls (i.e. are static objective-c methods inherently thread-safe) ?
If you know you are going to be on a background thread why not just use
+[NSURLConnection sendSynchronousRequest:returningResponse:error:]and be done with it?No fuzz with the run-loop needed. And if you only use local variables and the arguments you get thread safety with barely any work at all.
Otherwise thread safety is up to you independently of method type.
Class methods are not any bit more thread safe than instance methods. Both kinds of methods are in fact treaded just the same by the run-time. The class is actually an object instance of it’s meta-class, so a call to a class method is a normal method call to an object.