Let's suppose I have a Core Data model using AFIncrementalStore
, and I have multiple REST API endpoints for retrieving a list of objects of that model. I can override -requestForFetchRequest:withContext:
in AFHTTPClient
like so:
- (NSURLRequest *)requestForFetchRequest:(NSFetchRequest *)fetchRequest
withContext:(NSManagedObjectContext *)context {
NSMutableURLRequest *mutableURLRequest = nil;
if ([fetchRequest.entityName isEqualToString:@"Post"]) {
mutableURLRequest = [self requestWithMethod:@"GET" path:@"/posts/foo" parameters:nil];
}
return mutableURLRequest;
}
In this snippet, I retrieve Post
objects at /posts/foo
, but I also need to retrieve another set from /posts/bar
.
How can I do this? The only solution I see is to make two models: one for foo
and one for bar
, but repeating yourself is lame, and there may be many more API endpoints that get Post
objects for me that I'll need to support. Is there some other approach that I'm missing?
You need to inspect fetchRequest
more closely than just looking at entityName
. You can also look at fetchRequest.propertiesToFetch
or possibly other things depending on your data model. You'll still need to send two requests, so just make sure your AFNetworking subclass can tell the difference.
Also: it sounds like your requestForFetchRequest:withContext:
method might get really big. You might want to consider a more generic pattern in which you get your NSManagedObject
subclass, and ask that to return a fetch request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With