AFNetworking design pattern for wrapping REST requests/responses as objects - objective-c

I am working on an IOS project that uses AFNetworking 2.0 for REST communication. I am interested to know if there is a good design pattern for wrapping requests/responses as individual classes. I want to create a base class, say AbstractHTTPRequest that has basic completion code (i.e. was the request successful, checks etc) that will be common to all AbstractHTTPRequest derived classes.
One of the derived classes will be say a Sign-up request (SignupHTTPRequest) that derives from AbstractHTTPRequest. Then I want to have a "client" classes with methods corresponding to each request, say:
#interface MyHTTPClient
(SignupHTTPRequest *) newSignupRequest...;
#end
I want to know if anyone else wrapped the NSURLSessionDataTask / NSURLRequest etc classes used by AFNetworking into a coherent set of classes like I want to do. It is important for me to encapsulate the whole thing (logic, data, etc) into a class, but so far most attempts have been completely messy and I am not happy with it. The messy bit has to do with the fact that most approaches imply two sets of completion blocks. One used by the generic class (AbstractHTTPRequest) for the AFNetworking completions, then another set for the code that uses the actual HTTPRequest. You end up with this nasty chain of completion blocks.
Any ideas?
R

[Ideas...]
1)Elegancy. So you want to tag certain "classes" of code to always call some default convenience methods? Here's the relationship I see:
In human terms I would "delegate" a task to always be done by person1 because his role is "defined" when working with "me."
Does creating a objective-c protocols for delegates help? I'm reminded of pretty Python decorators but can't quite translate it.
2)Did I read BTL's right that you were trying ...finally blocks to indiscriminately run the common-calls?

Related

Which design pattern can I use to solve this situation?

First of all, I'm using Objective-C, but this doesn't matter at all.
My situation is:
I have two different scenarios. I distinguish them by a preprocessor macro like:
#ifdef USER
do some stuff for scenario 1
#else
do some stuff for scenario 2
Both scenarios works with a list of items all across the application, but the difference is the way of getting those items.
In the first one I get the items by sending a request to a server.
In the second one, I get them from the local device storage.
What I have now is the second scenario implemented. I have a singleton class that returns to me the list of items by getting them from the local storage. (like a traditional database singleton)
I want to add the other scenario. Since the items can be get from any point across the app, I want this to be a singleton too.
Does it make sense to have a singleton superclass, and then two subclasses that implement the different ways of getting the items? Singleton hierarchies sound quite strange to me.
That's not exactly hierarchy. The superclass you're mentioning is actually an interface for your 2 concrete classes, which can be singletons if you want. The interface is an abstract entity thus any instance-related term is irrelevant to it.
You're statically defining your program behavior by using preprocessor to do the scenario choice. If you stick to this approach and it fits your requirements, you don't need any design patterns. In your code just use the interface I mentioned above, which is a port to your statically instantiated data. If you want to have more flexibility (this sounds likely), you can do your scenario choice at runtime. In this case you may find the Strategy pattern useful for applying scenarios and Factory pattern for instancing.
Factory combined with Strategy.
Factory as the pattern of using another class to make your instance rather than using just a constructor. You are already doing that with your Singleton most likely.
Strategy for the ability to configure which kind of object is actually created by the factory at rutime.

xCode / Objective-C Anatomy Analogies - Help a Noob Get It

OK so I'm trying to get started with Xcode and I have some experience with OOP in general but mostly I'm used to scripting. Anyhoo, I'm trying to get a handle on some concepts in objective C and xcode and I'm having some problems putting everything together.
For starters, I'm having trouble understanding what delegates and protocols do. I think it would be useful if someone could explain this with a simple analogy of a postman, or a teacher, or a factory or something. I don't understand the difference between a method in a delegate and a regular class methods.
Say I have a Class Postman. Now postman has methods sortMail() and deleteMail(). What's an example of a delegate method. And if a delegate is used, where is the data returned? Inside the delegate? Do I have to instantiate the delegate and then read results from it or does the delegate kinda give the results back to the calling object? Where do protocols come in...
Simple examples please :) Baby steps.
Protocols and Delegates go together frequently. It helps to understand what a protocol is first.
Protocol
A protocol is a way of having a class promise to implement a standard set of methods.
Example: A certified electrician has a certain set of skills that all certified electricians will have. If you need someone to do something that a certified electrician is certified to do, then any certified electrician should be able to do it (in theory at least).
Delegate
Now a delegate is an object that has been given a responsibility to fulfill certain requirements. One object can be given the responsibility of fulfilling a need of another object.
Example: When building a house, the house needs to have wires run etc. This responsibility has been given to a certified electrician, and we know he can do it because he's certified (i.e. implements a certain protocol).
Putting it all together in a Cocoa context:
A UITableView needs cells supplied so it can display them. To supply the cells, a class will need to be created (or at least specified) which implements the UITableViewDataSource protocol. That guarantees that the class does the needed things to supply the UITableView with the needed cells.
So the UITableView delegates the responsibility of providing the cells to a certain class object which implements the protocol which guarantees that the object knows how to supply the needed cells.
Example
A delegate is an object that handles particular functionality for another object - as in "Object A delegates certain functionality to object B".
For instance, you may use an instance of Apple's class NSURLConnection to make a request for a web service, but Apple's code obviously won't know what to do with the data it downloads, so you provide a delegate object to handle that functionality. NSURLConnection then delegates that functionality to your object by passing it messages when it needs to do something like handle the data it downloads.
Another example is a table view. Apple have written a lot of code to display table views and handle interactions with them, but it doesn't know what data you want to display or what needs to be done with that data when somebody interacts with it. So you can provide delegate objects for these things. When a table view needs to know what data to display, it asks your delegate to fetch the data for it. When the user selects an item, it asks your delegate to handle it.
A protocol is simply a way of describing what messages the delegate is supposed to understand. There can be informal protocols, where it's just described in the documentation, and formal protocols, which are defined in a header file.

Choosing a Singleton or a Category?

Fairly early on in my app, when I was a lot less experienced than I am now, I wanted to spice up some transitions between view controllers with my own custom animations. Having no idea where to start, I looked around SO for a pattern like MVC that could be accessed from nearly any controller at any time, and as it turns out, a singleton was the way to go.
What I didn't realize is that there seems to be a strong and well-defended hatred of the singleton pattern, and I myself am starting to see why, but that is beside the point.
So, a while later, I decided to move my very same implementation into a category on UINavigationController (after all, it handles transitions!), kept the original classes around for comparison, and am wondering which method would work best. Having thoroughly tested both implementations, I can say without a doubt that they are equal in every way, including speed, accuracy, smoothness, frame-rate, memory usage, etc. so which one is 'better' in the sense of overall maintainability?
EDIT: after reading the well-written arguments you all have made, I have decided to use a singleton. #JustinXXVII has made the most convincing argument (IMHO), although I consider every answer here equally worthy of merit. Thank you all for your opinions, I have upvoted all answers in the question.
I believe the best option is use the category.
Because if you are already using UINavigationController, do not make sense create a new class that will only manage the transition, like you told: (after all, it handles transitions!)
This will be a better option to maintain your code, and you will be sure that the thing do what they expect to do, and if you already have an instance that do the transitions, why create another?
The design patterns, like singleton, factory, and others, need to be used with responsibility. In your case, I do not see why use a singleton, you use it only to no instantiate new objects, you do not really need to have only one instance of it, but you do it because you want only one.
I'll make the case for a singleton object. Singletons are used all over UIKit and iOS. One thing you can't do with categories is add instance variables. There are two things about this:
MVC workflows don't tolerate objects with intimate knowledge of other objects
Sometimes you just need a place to reference an object that doesn't really belong anywhere else
These things go against each other, but the added ability to be able to keep an instance variable that doesn't really have an "owner" is why I favor the singleton.
I usually have one singleton class in all of my XCode projects, which is used to store "global" objects and do mundane things that I don't want to burden my AppDelegate with.
An example would be serializing/archiving objects and unarchiving/restoring. I have to use the same method throughout several classes, I don't want to extend UIViewController with some serializing method to write and read arbitrary files. Maybe it's just my personal preference.
I also might need a quick way to lookup information in NSUserDefaults but not want to always be writing [[NSUserDefaults standardUserDefaults]stringForKey:#"blah"], so I will just declare a method in my singleton that takes a string argument.
Until now i've not really thought too much about using a category for these things. One thing is sure though, I'd rather not be instantiating a new object a hundred times to do the same task when I can have just one living object that sticks around and will take care of stuff for me. (Without burdening the AppDelegate)
I think that the real question is in "design" (as you said, both codes work fine), and by writing down your problem in simple sentences, you will find your answer :
singleton's purpose is to have only one instance of a class running in your app. So you can share things between objects. (one available to many objects)
category purpose is to extend the methods available to a class. (available to one class of objects only ! ok...objects from subclasses too)
what you really want is to make a new transition available to UINavigationController class. UINavigationController, which has already some method available to change view (present modal views, addsubviews, etc.) is built to manage views with transitions (you said it yourself, it handles transitions), all you want to do is adding another way of handling transitions for your navigation controllers thus you would preferably use a category.
My opinion is that what you want to achieve is covered by the category and by doing this you ensure that the only objects which are accessing this method are entitled to use it. With the singleton pattern, any object of any class could call your singleton and its methods (and... it could work nobody knowing how for an OS version n but your app could be broken in n+1 version).
In this implementation, for which there is no need to use a Singleton, there may be no difference at all. That doesn't mean that there isn't one.
A plastic bucket holds as much water as a metal bucket does, and it does it just as well. In that aspect there seems to be no difference between the two. However, if you try to transport something extremely hot, the plastic bucket might not do the job so well..
What I'm trying to say is, they both serve their purposes but in your case there seemed to be no difference because the task was too generic. You wanted a method that was available from multiple classes, and both solutions can do that.
In your case, however, it might be a whole of a lot simpler to use a Category. The implementation is easier and you (possibly) need less code.
But if you were to create a data manager that holds an array of objects that you ONLY want available at one place, a Category will not be up to the task. That's a typical Singleton task.
Singeltons are single-instance objects (and if made static, available from nearly everywhere). Categories are extensions to your existing classes and limited to the class it extends.
To answer your question; choose a Category.
*A subclass might also work, but has its own pros and cons
Why don't you simply create a base UIViewController subclass and extend all of your view controllers from this object? A category doesn't make sense for this purpose.
Singletons, as the name suggests, has to be used when there is a need to be exactly one object in your application. The pattern for the accessor method ensures only this requirement being a class method:
+ (MyClass*) sharedInstance
{
static MyClass *instance = nil;
if (instance == nil) instance = [[MyClass alloc] init];
return instance;
}
If implemented well, the class also ensures that its constructor is private thus nobody else can instantiate the class but the accessor method: this ensures that at any time at most one instance of the class exists. The best example of such class is UIApplication since at any time there might be only one object of this class.
The point here is that this is the only requirement towards singleton. The role of the accessor method is to ensure that there is only one instance, and not that it would provide access to that instance from everywhere. It is only a side effect of the pattern that, the accessor method being static, everybody can access this single object without having a reference (pointer) to it a priori. Unfortunately this fact is widely abused by Objective C programmers and this leads to messed up design and the hatred towards singleton pattern you mentioned. But all in all it is not the fault the singleton patter but the misuse of their accessor method.
Now turning back to your question: if you don't need static / global variables in your custom transition code (I guess you don't) then the answer is definitely go for categories. In C++ you would subclass from some parent BaseTransition class and implement your actual drawing methods. Objective C has categories (that in my opinion is another way that easily messes up the design, but they are much more convenient) where you can add custom functionality even accessing the variables of your host class. Use them whenever you can redeem singletons with them and don't use singletons when the main requirement towards your class is not that it would be only one instance of it.

When to use Categories

I've recently discovered categories and was wondering when it might be appropriate to use them in a user defined class/new class. For example, I can see the benefits of adding a category to an existing class like NSString, but when creating a new class what would be the advantage of adding a category to this rather than just implementing a normal method?
Hope this makes sense.
Many thanks
Jules
The answer isn't really any different for your own classes than it is for framework classes. If you have multiple projects, you'll likely end up sharing some classes between them. However, you may want to extend some of your classes so that they work more easily with a specific project, but not want to include those extra methods in your other projects, where they might not make sense. You can use a category to extend your class without needing to subclass.
If I understand your question correctly, creating a "new class" is always "subclassing" because you're subclassing NSObject at the very least.
You could use categories on a new class to separate out sections of responsibility of a complex class. For example, all the basic functionality (instance variables, accessors, description, etc.) can go in one file (the "main" class file) while all methods to support a protocol (such as NSTableViewDataSource) can go in another.
Some take this approach to keep things "neat". I'm a firm believer in "if it's my own custom class, all its code should be in one file" so I do not personally do this. I demarcate different logical aspects of the class' code with "#pragma mark Some Section Name" to help navigation and readability. Your mileage may vary.
Adding a Category on NSString is useful when you want to call a method on every single NSString instance you will encounter. This is a real improvement over inheritance for this kind of object because they are used by the core framework and you don't have to convert a NSString object to your subclass when you want to call your custom method.
On the other hand, you can just put methods in, no instance variables.
In the book Refactoring by Martin Fowler, he has a section titled "Introduce Foreign Method" (A server class you are using needs an additional method, but you can't modify the class.) That's what categories are good for.
That said, there are times when using a category, instead of changing the class, is appropriate. A good example on using a category, even though you could change the server class, is how Apple handled the UIViewController MediaPlayer Additions. They could have put these two methods in UIViewController itself but since the only people who would ever use them are people who are using the Media Player framework, it made more sense to keep the methods there.

Discover subclasses of a given class in Obj-C

Is there any way to discover at runtime which subclasses exist of a given class?
Edit: From the answers so far I think I need to clarify a bit more what I am trying to do. I am aware that this is not a common practice in Cocoa, and that it may come with some caveats.
I am writing a parser using the dynamic creation pattern. (See the book Cocoa Design Patterns by Buck and Yacktman, chapter 5.) Basically, the parser instance processes a stack, and instantiates objects that know how to perform certain calculations.
If I can get all the subclasses of the MYCommand class, I can, for example, provide the user with a list of available commands. Also, in the example from chapter 5, the parser has an substitution dictionary so operators like +, -, * and / can be used. (They are mapped to MYAddCommand, etc.) To me it seemed this information belonged in the MyCommand subclass, not the parser instance as it kinda defeats the idea of dynamic creation.
Not directly, no. You can however get a list of all classes registered with the runtime as well as query those classes for their direct superclass. Keep in mind that this doesn't allow you to find all ancestors for the class up the inheritance tree, just the immediate superclass.
You can use objc_getClassList() to get the list of Class objects registered with the runtime. Then you can loop over that array and call [NSObject superclass] on those Class objects to get their superclass' Class object. If for some reason your classes do not use NSObject as their root class, you can use class_getSuperclass() instead.
I should mention as well that you might be thinking about your application's design incorrectly if you feel it is necessary to do this kind of discovery. Most likely there is another, more conventional way to do what you are trying to accomplish that doesn't involve introspecting on the Objective-C runtime.
Rather than try to automatically register all the subclasses of MYCommand, why not split the problem in two?
First, provide API for registering a class, something like +[MYCommand registerClass:].
Then, create code in MYCommand that means any subclasses will automatically register themselves. Something like:
#implementation MYCommand
+ (void)load
{
[MYCommand registerClass:self];
}
#end
Marc and bbum hit it on the money. This is usually not a good idea.
However, we have code on our CocoaHeads wiki that does this: http://cocoaheads.byu.edu/wiki/getting-all-subclasses
Another approach was just published by Matt Gallagher on his blog.
There's code in my runtime browser project here that includes a -subclassNamesForClass: method. See the RuntimeReporter.[hm] files.