带有嵌套资源的afrestclientpathforentity



我试图在相册中获取照片,使用嵌套的资源url,如:

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

似乎最简单的方法是在我的AFRESTClient子类中重写pathForEntity函数。但是,我没有访问专辑对象的权限,因此我不能返回包含album_id的URL。我应该如何覆盖/扩展来实现这一点?看看下面我是如何做到这一点的,注意在我不能提供专辑ID的地方有问号:

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

在堆栈的上方,我在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];
}

谢谢!

我们有一个类似的层次结构,最终在我们的AFRESTClient子类中实现了pathForRelationship:forObject:方法。对于相册和照片,我想应该是这样的:

- (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];
}

这是假设您在模型中设置了many关系。

相关内容

  • 没有找到相关文章

最新更新