I am using a iOS library called Restkit, which automatically maps remote objects to local objects. You do that by creating a mapping using KVC pattern, and then loading with the mapping.
While I understand how it works, I don’t understand why some parts are implemented in certain ways. For example it uses a singleton pattern where you create an instance of RKObjectMapping like below:
RKObjectMapping* articleMapping = [RKObjectMapping mappingForClass:[Article class]];
[articleMapping mapKeyPath:@"title" toAttribute:@"title"];
[articleMapping mapKeyPath:@"body" toAttribute:@"body"];
[articleMapping mapKeyPath:@"author" toAttribute:@"author"];
[articleMapping mapKeyPath:@"publication_date" toAttribute:@"publicationDate"];
However, when it comes time to actually use it, you access the manager by calling sharedManager of the class RKObjectManager, like following:
[[RKObjectManager sharedManager].mappingProvider setMapping:articleMapping
forKeyPath:@"articles"];
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/articles"
delegate:self];
What I don’t understand is, why even bother instantiating the class as articleMapping, when you will just access it using a class method/variable like sharedManager? Why not do something like:
[RKObjectMapping initWithClass:[Article class]];
I am a newbie so think there would be a good reason for taking this pattern that I am not aware of. Anyone know or understand why this would be implemented in this way?
When an object needs to access data associated to itself, it uses instance variables (ivars) to store that data. However, instance variables are part of a specific instance of the class and not the class itself – from a class method, they cannot be accessed. So, when the manager class you’re talking about was to store/access its private data, it uses a shared instance (singleton) to create instance variables. If it was used only as a class, it had to store its private data in global variables, which is considered bad practice in C.
Also, if you look closely, the
RKObjectManagerclass has properties. In Objective-C, properties are always backed by an underlying instance variable (be it created at runtime, dynamically, or at compile time, in a declared manner) – that’s why classes can’t have properties, and that’s why a singleton (an actual instance of a class) is needed.Example without singleton (ugly):
Example with singleton (much better):