2

我正在尝试使用嵌套资源 URL 获取相册中的照片,例如:

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

似乎最简单的方法是在我的 AFRESTClient 子类中覆盖 pathForEntity 函数。但是,我无权访问专辑对象,因此无法返回包含专辑 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];
}

谢谢!

4

1 回答 1

0

我们有一个类似的层次结构,最终在我们的 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];
}

这是假设您的模型中有 toMany 关系设置。

于 2013-09-08T02:54:10.890 回答