2

So I have this service class that utilize Restkit to consume REST web services. It is frequently used in my app. Instead of initialize it every time before using it, I create an object of this class and init it in appDelegate. But is this the best way to do so?

I thought about using singleton, but was a bit concerned about it in multi-threading environment. Any suggestions will be really appreciated. Thanks!

EDIT: I should mention that I work in ARC environment.

Robert Kang
  • 568
  • 5
  • 19

2 Answers2

2

There's nothing wrong with a singleton pattern even in a multithreaded or ARC environment as long as the objects data is either read-only or protected. When I write classes like this, I use a singleton and use GCD to protect access to the very few mutable data structures it uses (like the list of current requests being fulfilled by it and the completion blocks to execute when they're done).

If you're supporting iOS 5+ or Mac OS X 10.7+ the new private concurrent queues and barriers make this even more efficient. I don't know about RestKits multithreading so you might need to check that but I'd still recommend a singleton.

Jason Coco
  • 77,985
  • 20
  • 184
  • 180
1

ARC doesn't really matter. So long as you understand the negative aspects of singletons and are prepared to have that or deal with it, the pattern works fine.

What I suggest as an alternative is to design a static class and use the Provider pattern. This is a typical interface I use with RESTKit (this one accesses the facebook graph API).

@interface FBProvider : NSObject

+ (BOOL) canMakeRequests;
+ (id) login;
+ (id) logout;

+ (BOOL) application: (UIApplication*) application 
             openURL: (NSURL*) url 
   sourceApplication: (NSString*) sourceApplication 
          annotation: (id) annotation;

+ (id) perform: (RKRequestMethod) method friends: (Friend*) frien;
+ (id) perform: (RKRequestMethod) method boasts: (id) obj;
+ (id) perform: (RKRequestMethod) method invites: (id)obj;
+ (id) perform: (RKRequestMethod) method likes: (id)obj;

@end

There is no singleton, everything is static and if you design your interface to operate from your app data model and NOT your web service UI updates happen automatically.

Alternatively, if you feel you must use a singleton why not utilize your app delegate which is a true singleton. To expand, I am suggesting your web service or data provider becomes a member of an existing singleton and you will never have to worry about threading issues yourself because hopefully these are handled by Cocoa.

Community
  • 1
  • 1
Paul de Lange
  • 10,613
  • 10
  • 41
  • 56