【问题标题】:AFRESTClient pathForEntity with nested resources?具有嵌套资源的 AFRESTClient pathForEntity?
【发布时间】:2013-01-02 18:22:03
【问题描述】:

我正在尝试使用嵌套资源 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];
}

谢谢!

【问题讨论】:

  • 您找到解决方案了吗?

标签: ios afnetworking afincrementalstore


【解决方案1】:

我们有类似的层次结构,最终在我们的 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 关系。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-21
    • 2011-08-23
    • 2014-08-02
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多