2013-12-12 58 views
3

我想使用RestKit(即能夠在請求後調用user.photos並使它們自動映射)在覈心數據中擁有其擁有User對象的GET響應照片。然而,我不明白我如何設置它自動執行,而我必須明確地使用[user setPhotos:...]RKMappingResultRestKit映射未擁有的關係到擁有對象

有沒有一種方法可以使用映射和響應描述符自動實現這一點?

路線/響應描述:

RKRoute *userPhotos = [RKRoute routeWithRelationshipName:@"photos" objectClass:[User class] pathPattern:@"/api/v1/photos" method:RKRequestMethodGET]; 
[[[[APIClient objectManager] router] routeSet] addRoute:userPhotos]; 

RKResponseDescriptor *photosDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:self.photoMapping 
                         method:RKRequestMethodGET 
                       pathPattern:nil 
                        keyPath:kJsonPhotos 
                        statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]; 
[[[APICacheStore sharedStore] objectManager] addResponseDescriptorsFromArray:@[photosDescriptor]]; 

代碼:

+ (void)getPhotosForUser:(User *)user success:(void (^)())success failure:(void (^)(NSString *errorMsg))failure { 
    NSAssert(user, @"User must not be nil when we attempt to fetch their photos."); 
    [[APIClient objectManager] getObjectsAtPathForRelationship:@"photos" ofObject:user parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { 
    [user setPhotos:[NSSet setWithArray:[mappingResult array]]]; 
    success(); 
    } failure:^(RKObjectRequestOperation *operation, NSError *error) { 
    NSLog(@"Error: %@", error); 
    failure(error.localizedDescription); 
    }]; 
} 

原始JSON:

{ 
    "meta": { 
    "total": 2, 
    "offset": 0, 
    "limit": 10 
    }, 
    "photos": [ 
    { 
     "id": "d8e1ca59-9f50-4963-8e7e-0b0c8de4bed6", 
     "name": "Mary at the mall", 
     "updated_at": "2013-12-11T10:16:41.000Z", 
     "completed_at": null, 
     "created_at": "2013-12-11T10:16:41.000Z", 
     "image": "images/is9912zh/image.jpeg" 
    }, 
    { 
     "id": "1c75273a-7675-43a9-9b62-3d4236439ec6", 
     "name": "John at the park", 
     "updated_at": "2013-12-11T10:16:41.000Z", 
     "completed_at": null, 
     "created_at": "2013-12-11T10:16:41.000Z", 
     "image": "images/aj92j127/image.jpeg" 
    } 
    ] 
} 

回答

1

不跟你似乎有可用的信息和方式,你」重新發送請求。

如果路徑模式是@"/api/v1/photos/##USER_ID##"那麼路由將爲外鍵映射提供足夠的信息。如果返回的JSON具有用戶標識,那麼將爲外鍵映射提供足夠的信息。

從技術上講,操作具有填充關係所需的所有信息,但RestKit不會(當前)嘗試執行此操作。你可以看看實現這個並提交一個拉請求。

+0

再次感謝Wain! – ZeNewb

+0

有什麼你*不知道的*關於RestKit? –

+0

@MartinR好吧,我沒有閱讀所有的代碼,所以我有時會做出錯誤的假設;) – Wain