Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have multiple URL requests to fetch a single type of entity in AFIncrementalStore?

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?

like image 667
greenisus Avatar asked Nov 02 '22 18:11

greenisus


1 Answers

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.

like image 52
Aaron Brager Avatar answered Nov 14 '22 01:11

Aaron Brager