4

I'm using AFNetworking for all my connections in my app. I created a singleton 'client' class that takes care of all the AFNetworking code and uses AFHTTPRequestOperationManager. What I am confused about is whether the AFHTTPRequestOperationManager object should be a property, or should I recreate one everytime my client is asked for a connection? If it is a property, can my client be called many times asynchronously, or will that cause problems, since the same instance of AFHTTPRequestOperationManager will be used possibly at the same time ?

David Snabel-Caunt
  • 57,804
  • 13
  • 114
  • 132
koen
  • 5,383
  • 7
  • 50
  • 89
  • @DavidCaunt I haven't tried a property but I did try storing the manager to an instance variable and I've had bad access crashes. For some reason, the instance I've assigned to my variable died. So I think initializing a new manager upon usage (local variable) is better (it's the fix i did). By the way, I'm using ARC so an instance variable should have a strong pointer to the object assigned by default much like how a strong property works. – cessmestreet Apr 11 '15 at 16:05

1 Answers1

4

Typically, your singleton 'client' class would be a subclass of AFHTTPRequestOperationManager. It could also be a property, but then you won't be able to override methods. Some commonly overridden methods are:

  • - HTTPRequestOperationWithRequest:success:failure:, to modify how all request operations are constructed (for example, if you need an identical header in every request)
  • – initWithBaseURL:, to apply additional customization to the operation manager

That said, a property could work fine depending on your needs. (See Prefer composition over inheritance? for some delightful weekend reading.)

And finally:

If it is a property, can my client be called many times asynchronously, or will that cause problems, since the same instance of AFHTTPRequestOperationManager will be used possibly at the same time?

Yes, AFHTTPRequestOperationManager is designed to be thread-safe. You can tell it to do stuff from different threads. (Note that its completion blocks are always called on the main thread, since UI work is typically done there.)

Community
  • 1
  • 1
Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
  • I choose to not subclass `AFHTTPRequestOperationManager` since eventually I want to switch to `AFURLSessionManager ` when my app drops iOS6 support. Having a neutral client seems to be better for a smooth transition (but I could be mistaken). I will accept your question for answering the question regarding `AFHTTPRequestOperationManager` being thread safe. – koen Jan 28 '14 at 16:41
  • @Koen Yes, that's a good reason to use a property. For the sake of argument, though, you could use subclassing and do the same thing with a class cluster. (Your class could return a different subclass instance depending on the current iOS version.) – Aaron Brager Jan 28 '14 at 17:59