2013-10-08 3 views
0

Я проверил вопросы, похожие на мои проблемы (например, this и this), но мне не удалось найти решение для моей проблемы. Я попытался отобразить свои данные с помощью учебника от Restkit's object mapping page, но мне не удалось получить нужные результаты. Если кто-то может указать на мою ошибку, я бы очень признателен.Reskit 0.20.1 mapping JSON valueForUndefinedKey error

Моя проблема

мое приложение вылетает, когда я пытаюсь получить данные, как и я получаю «этот класс не является значение ключа кодирования совместимый для ключа 'GameID.». Я считаю, что я сопоставляю элемент и неправильно отвечает на массивы.

JSON, что я пытаюсь Карта

образец:

{ 
    "GameId": 1, 
    "Items": [ 
    { 
     "Id": 1, 
     "PicUrl": "sample string 2", 
     "Answers": [ 
     "sample string 1", 
     "sample string 2", 
     "sample string 3" 
     ], 
     "CorrectAnswer": "sample string 3", 
     "Difficulty": 4, 
     "CategoryId": 5, 
     "CategoryName": "sample string 6", 
     "AccountId": 7 
    }, 
    { 
     "Id": 1, 
     "PicUrl": "sample string 2", 
     "Answers": [ 
     "sample string 1", 
     "sample string 2", 
     "sample string 3" 
     ], 
     "CorrectAnswer": "sample string 3", 
     "Difficulty": 4, 
     "CategoryId": 5, 
     "CategoryName": "sample string 6", 
     "AccountId": 7 
    }, 
    { 
     "Id": 1, 
     "PicUrl": "sample string 2", 
     "Answers": [ 
     "sample string 1", 
     "sample string 2", 
     "sample string 3" 
     ], 
     "CorrectAnswer": "sample string 3", 
     "Difficulty": 4, 
     "CategoryId": 5, 
     "CategoryName": "sample string 6", 
     "AccountId": 7 
    } 
    ], 
    "StartTime": "2013-10-07T00:24:22.0048045+00:00" 
} 

Мой класс данных

CurrentGames.h

#import <Foundation/Foundation.h> 

@interface CurrentGames : NSObject 

@property (nonatomic,retain) NSNumber *GameId; 
@property(nonatomic,strong)NSArray *items; 
@property(nonatomic,retain) NSNumber *ID; 
@property(nonatomic,retain) NSURL *pictureUrl; 
@property (nonatomic,strong) NSArray *answers; 
@property(nonatomic,retain) NSString *ans1; 
@property (nonatomic,retain)NSString *ans2; 
@property(nonatomic,retain)NSString *ans3; 
@property (nonatomic,retain)NSString *ans4; 
@property(nonatomic,retain) NSString *correctAnswer; 
@property(nonatomic,retain) NSString *difficulty; 
@property(nonatomic,retain) NSString *categoryID; 
@property(nonatomic,retain)NSString *categoryName; 
@property(nonatomic,retain)NSString *accountID; 

@end 

CurrentGames.m

#import "CurrentGames.h" 

@implementation CurrentGames 

- (id)init 
{ 
    self = [super init]; 
    if (self) 
    { 
     _answers = [[NSArray alloc]initWithObjects:_ans1,_ans2,_ans3,_ans4, nil]; 
     _items =[[NSArray alloc]initWithObjects:_ID,_pictureUrl,_answers,_correctAnswer,_categoryID,_categoryName,_accountID, nil]; 

    } 
    return self; 
} 

@end 

Путь Стараюсь карту

-(void)loadGame 
{ 
    RKObjectMapping* currentGameMapping = [RKObjectMapping mappingForClass:[CurrentGames class]]; 
    [currentGameMapping addAttributeMappingsFromDictionary:@{ 
                  @"GameId":@"GameId", 
                  @"Items": @"items", 
                  @"Id":@"ID", 
                  @"PicUrl":@"pictureUrl", 
                  @"Answers":@"answers", 
                  @"CorrectAnswer": @"correctAnswer", 
                  @"Difficulty":@"difficulty", 
                  @"CategoryId":@"categoryID", 
                  @"CategoryName":@"categoryName", 
                  @"AccountId":@"accountID", 


                  }]; 
    RKResponseDescriptor *responseDescriptor =[RKResponseDescriptor responseDescriptorWithMapping:currentGameMapping method:RKRequestMethodGET pathPattern:nil keyPath:@"GameId" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]; 

    NSURL *URL = [NSURL URLWithString:@"https://picquiz.azurewebsites.net/Games/Current/13"]; 

    NSURLRequest *request =[NSURLRequest requestWithURL:URL]; 

    RKObjectRequestOperation *objectRequestOperation =[[RKObjectRequestOperation alloc]initWithRequest:request responseDescriptors:@[responseDescriptor]]; 

    [objectRequestOperation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { 
     RKLogInfo(@"Load collection of Articles: %@", mappingResult.array); 
    } failure:^(RKObjectRequestOperation *operation, NSError *error) { 
     RKLogError(@"Operation failed with error: %@", error); 
    }]; 

    [objectRequestOperation start]; 
    } 

Консоль

2013-10-07 20:16:38.824 FlickRest[1253:a0b] I restkit:RKLog.m:34 RestKit logging initialized... 
2013-10-07 20:16:38.952 FlickRest[1253:a0b] I restkit.network:RKObjectRequestOperation.m:180 GET 'https://picquiz.azurewebsites.net/Games/Current/13' 
2013-10-07 20:16:39.622 FlickRest[1253:3407] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFNumber 0x8bb3080> valueForUndefinedKey:]: this class is not key value coding-compliant for the key GameId.' 
*** First throw call stack: 
(
    0 CoreFoundation      0x020ca5e4 __exceptionPreprocess + 180 
    1 libobjc.A.dylib      0x01e4d8b6 objc_exception_throw + 44 
    2 CoreFoundation      0x0215a6a1 -[NSException raise] + 17 
    3 Foundation       0x00c95b0a -[NSObject(NSKeyValueCoding) valueForUndefinedKey:] + 282 
    4 Foundation       0x00c02b61 _NSGetUsingKeyValueGetter + 81 
    5 Foundation       0x00c0219b -[NSObject(NSKeyValueCoding) valueForKey:] + 260 
    6 Foundation       0x00c21c9a -[NSObject(NSKeyValueCoding) valueForKeyPath:] + 409 
    7 FlickRest       0x0007e891 -[RKMappingSourceObject valueForKeyPath:] + 833 
    8 FlickRest       0x00083ea7 -[RKMappingOperation applyAttributeMappings:] + 1671 
    9 FlickRest       0x0008b89e -[RKMappingOperation main] + 4062 
    10 Foundation       0x00ca9a69 -[__NSOperationInternal _start:] + 671 
    11 Foundation       0x00c26798 -[NSOperation start] + 83 
    12 FlickRest       0x00078f25 -[RKMapperOperation mapRepresentation:toObject:atKeyPath:usingMapping:metadata:] + 1957 
    13 FlickRest       0x000777a0 -[RKMapperOperation mapRepresentation:atKeyPath:usingMapping:] + 1904 
    14 FlickRest       0x0007a11d -[RKMapperOperation mapRepresentationOrRepresentations:atKeyPath:usingMapping:] + 829 
    15 FlickRest       0x0007aa72 -[RKMapperOperation mapSourceRepresentationWithMappingsDictionary:] + 2210 
    16 FlickRest       0x0007b43b -[RKMapperOperation main] + 1403 
    17 Foundation       0x00ca9a69 -[__NSOperationInternal _start:] + 671 
    18 Foundation       0x00c26798 -[NSOperation start] + 83 
    19 FlickRest       0x000cb7da -[RKObjectResponseMapperOperation performMappingWithObject:error:] + 1354 
    20 FlickRest       0x000c9813 -[RKResponseMapperOperation main] + 2371 
    21 Foundation       0x00ca9a69 -[__NSOperationInternal _start:] + 671 
    22 Foundation       0x00c26798 -[NSOperation start] + 83 
    23 Foundation       0x00cabd34 __NSOQSchedule_f + 62 
    24 libdispatch.dylib     0x028de4b0 _dispatch_client_callout + 14 
    25 libdispatch.dylib     0x028cc088 _dispatch_queue_drain + 450 
    26 libdispatch.dylib     0x028cbe85 _dispatch_queue_invoke + 126 
    27 libdispatch.dylib     0x028cce25 _dispatch_root_queue_drain + 83 
    28 libdispatch.dylib     0x028cd13d _dispatch_worker_thread2 + 39 
    29 libsystem_c.dylib     0x02bf6e72 _pthread_wqthread + 441 
    30 libsystem_c.dylib     0x02bdedaa start_wqthread + 30 
) 
libc++abi.dylib: terminating with uncaught exception of type NSException 
Program ended with exit code: 0 

ответ

0

Ваша проблема заключается в том, что ваш дескриптор ответа устанавливает keyPath:@"GameId", это должно быть на самом деле keyPath:nil. Ваша текущая конфигурация заставляет все ваши сопоставления применяться к экземпляру NSNumber (который, очевидно, не будет работать).

+0

спасибо ответ Wain. Я повторно написал отображение, основанное на обзоре отображения объектов Restkit (теперь это более понятно), а также установите keyPath в nil. Но у меня все еще есть проблемы. Не могли бы вы взглянуть на него? [ссылка на вопрос] (http://stackoverflow.com/questions/19262700/mapping-with-restkit-with-relationships-and-no-key-path-for-some-part-of-the-dat) – Matt

Смежные вопросы