a10s
a10s

Reputation: 970

AFRESTClient pathForEntity with nested resources?

I am trying to get photos in an album, using nested resource URLs, like:

GET http://www.myapi.com/albums/:album_id/photos

It seems like the driest way to accomplish this is by overriding the pathForEntity function in my subclass of AFRESTClient. However, I don't have access to the album object, so I can't return the URL including the album_id. How should I override/extend to accomplish this? See below for how I was trying to do this, note the question marks where I can't provide the album ID:

- (NSString *)pathForEntity:(NSEntityDescription *)entity {

  NSString *path = AFPluralizedString(entity.name);

  if ([entity.name isEqualToString:@"Photo"]) {
    path = [NSString stringWithFormat:@"albums/%d/photos", ??];
  }

  return path;
}

Higher up the stack, I have this in PhotosViewController -viewDidLoad

- (void)viewDidLoad
{
  [super viewDidLoad];

  self.title = self.currentAlbum.name;

  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Photo"];
  fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"createdAt" ascending:NO]];

  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"album == %@", self.currentAlbum];
  fetchRequest.predicate = predicate;

  self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
  self.fetchedResultsController.delegate = self;
  [self.fetchedResultsController performFetch:nil];
}

Thanks!

Upvotes: 2

Views: 306

Answers (1)

Tim Ritchey
Tim Ritchey

Reputation: 181

We have a similar hierarchy, and end up implementing the pathForRelationship:forObject: method in our AFRESTClient subclass. In your case for Albums and Photos, I'd imagine it would be something like:

- (NSString *)pathForRelationship:(NSRelationshipDescription *)relationship
                        forObject:(NSManagedObject *)object
{
    if ([object isKindOfClass:[Album class]] && [relationship.name isEqualToString:@"photos"]) {
        Album *album = (Album*)object;
        return [NSString stringWithFormat:@"/albums/%@/photos", album.album_id];
    }
    return [super pathForRelationship:relationship forObject:object];
}

This is assuming you have the toMany relationship setup in your model.

Upvotes: 0

Related Questions