0
我正在嘗試使用RestKit來解析某些JSON。該應用程序用於跟蹤比賽,並具有場地,遊戲和玩家的概念。一場比賽有贏家和輸家(都是班級玩家)和一個場地。由Web服務返回的JSON看起來是這樣的:ResKit對象映射嵌套對象
[{"id":1,"winner":{"name":"NAME2","id":2,"picture_url":"CK.png"},"loser":{"name":"NAME3","id":3,"picture_url":"NJ.png"},"venue":{"name":"Venue 1","id":2}},
{"id":2,"winner":{"name":"NAME2","id":2,"picture_url":"CK.png"},"loser":{"name":"NAME1","id":1,"picture_url":"NC.png"},"venue":{"name":"Venue 1","id":2}},
{"id":3,"winner":{"name":"NAME2","id":2,"picture_url":"CK.png"},"loser":{"name":"NAME3","id":3,"picture_url":"NJ.png"},"venue":{"name":"Venue 1","id":2}},
{"id":4,"winner":{"name":"NAME2","id":2,"picture_url":"CK.png"},"loser":{"name":"NAME1","id":1,"picture_url":"NC.png"},"venue":{"name":"Venue 1","id":2}}]
我對象的頭文件是這樣的:
# PTGame.h
@interface PTGame : NSObject
@property (nonatomic, assign) NSNumber *uid;
@property (nonatomic, assign) PTPlayer *winner;
@property (nonatomic, assign) PTPlayer *loser;
@property (nonatomic, assign) PTVenue *venue;
@end
# PTVenue.h
@interface PTVenue : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSNumber *uid;
-(CLLocation *)location;
-(CLLocationDistance)distanceFromLocation:(CLLocation *)location;
@end
# PTPlayer.h
@interface PTPlayer : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *pictureUrl;
@property (nonatomic, assign) NSNumber *uid;
@end
最後,我映射設置的樣子:
RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];
RKObjectMapping *venueMapping = [RKObjectMapping mappingForClass:[PTVenue class]];
[venueMapping addAttributeMappingsFromDictionary:@{@"name" : @"name",
@"id" : @"uid"}];
RKObjectMapping *playerMapping = [RKObjectMapping mappingForClass:[PTPlayer class]];
[playerMapping addAttributeMappingsFromDictionary:@{@"name" : @"name",
@"id" : @"uid",
@"picture_url": @"pictureUrl"}];
// Add Object Mapping for PTGame
RKObjectMapping *gameResponseMapping = [RKObjectMapping mappingForClass:[PTGame class]];
// Setup Game Object relationships
[gameResponseMapping addAttributeMappingsFromDictionary:@{@"id": @"uid"}];
[gameResponseMapping addRelationshipMappingWithSourceKeyPath:@"winner" mapping:playerMapping];
[gameResponseMapping addRelationshipMappingWithSourceKeyPath:@"loser" mapping:playerMapping];
[gameResponseMapping addRelationshipMappingWithSourceKeyPath:@"venue" mapping:venueMapping];
NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);
RKResponseDescriptor *gameListResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:gameResponseMapping
method:RKRequestMethodGET
pathPattern:@"/games.json"
keyPath:nil
statusCodes:statusCodes];
[objectManager addResponseDescriptor:gameListResponseDescriptor];
這一切看起來很適合我。返回結果時不會引發錯誤,但稍後在嘗試訪問遊戲屬性時會出現異常。通過XCode調試器查看對象顯示:
某些東西似乎被打破 - 爲什麼這些字符串顯示爲「贏家」和「場地」。爲什麼uid
爲空?每當我提出請求時,對象似乎都不一樣,導致我相信內存處理不當。
任何想法?
是對象正確的映射後的代碼看起來不錯? 。建議在其他地方進行內存管理。在崩潰之前運行哪些代碼? – Wain