我正在尝试使用嵌套资源网址在相册中获取照片,例如:
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];
}
谢谢!
答案 0 :(得分: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关系。