-
Notifications
You must be signed in to change notification settings - Fork 0
Using Multiple Base URLs (and Multiple Object Managers)
Sometimes your application needs to access more than one REST web service to accumulate all the data you need. You may be tempted to alter the shared object manager's client BaseURL whenever you're loading data from different servers. However, each time you change the client, RestKit must reestablish network reachability, which takes time. Moreover, you may also introduce additional more serious problems in other application threads when the expected base URL suddenly changes for the shared object manager and client. Thankfully, RestKit's developers have included another mechanism to satisfy the need for loading data from multiple servers. So, don't change your main object manager's BaseURL ... simply create another object manager and suffer no side-effects! If you create this second object manager relatively early in the life cycle of your application, it can establish reachability earlier, perhaps avoiding an otherwise delayed response to your subsequent queries.
The first object manager you create will be the shared singleton RestKit uses by default. But by creating additional object managers, you can pull from their BaseURLs as needed, just be sure to retain these new managers. The following snippet comes from Andras Hatvani (@andrashatvani):
RKObjectManager *flickrManager =
[RKObjectManager objectManagerWithBaseURL:flickrBaseUrl]; // <-- shared singleton
RKObjectManager *foursquareManager =
[[RKObjectManager objectManagerWithBaseURL:foursquareBaseUrl] retain]; // <-- you must retain every other instance.
Depending on your application, you may want to put this second object manager in a more accessible place, like a retained property on the AppDelegate, so that it's easy to pull from as needed.
In the event that you need to differentiate between the results from your two (or more) object managers, simply set an identifier in the userData for the queries. From Blake Watters (@blakewatters):
- (void)someAction(id)sender {
// .......
RKObjectLoader* loader = [[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/whatever" delegate:self];
loader.userData = @"foursquare";
// or do this, if you need a number instead of a string
loader.userData = [NSNumber numberWithInt:1234];
// .......
}
//Then when the delegate comes back you can cast it into a string or number as appropriate:
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
// .......
NSString* source = (NSString*) objectLoader.userData;
// or, if you did the NSNumber instead:
NSNumber* source = (NSNumber*) objectLoader.userData;
// .......
}