无法使用RestKit检索数据,因为类不符合键值编码

时间:2013-04-29 17:16:57

标签: restkit tastypie

我正在为iOS编写一个简单的多项选择题。

我想创建一个API,以便我可以检索问题并存储用户的答案。我使用django和tastypie作为后端。

我使用此功能在我的应用中加载问题:

- (void)loadQuestion
{
RKObjectMapping* questionMapping = [RKObjectMapping mappingForClass:[Question class]];
[questionMapping addAttributeMappingsFromDictionary:@{
 @"question": @"question",
 }];

RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:questionMapping pathPattern:nil keyPath:@"question" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];

NSURL *URL = [NSURL URLWithString:@"http://127.0.0.1:8000/api/v1/question/2/?format=json"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSLog(@"request : %@", request);
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];
}

这是我的问题:

#import <Foundation/Foundation.h>

@interface Question : NSObject

@property (strong) NSString *question;

@end

我的问题.m

@implementation Question

@synthesize question = _question;

@end

JSON如下:

{
"chapter": "/api/v1/chapter/2/", 
"id": 2, "
pub_date": "2013-04-25T19:23:42.930097", 
"question": "Quelle est la capitale de ce pays : Emirats Arabes Unis ?", 
"resource_uri": "/api/v1/question/2/"
}

tastypie API是:

from tastypie.resources import ModelResource
from tastypie import fields

from .models import Question, Chapter

class ChapterResource(ModelResource):
class Meta:
    queryset = Chapter.objects.all()
    resource_name = 'chapter'

class QuestionResource(ModelResource):
chapter = fields.ForeignKey(ChapterResource, 'chapter')

class Meta:
    queryset = Question.objects.all()
    resource_name = 'question'

我得到的错误是: 由于未捕获的异常'NSUnknownKeyException'而终止应用程序,原因:'[&lt; __ NSCFString 0x76b3030&gt; valueForUndefinedKey:]:这个类不是关键问题的键值编码兼容。'

我看了https://github.com/RestKit/RestKit/wiki/Object-Mapping,但没有找到我做错的事。

我班上有什么问题?

1 个答案:

答案 0 :(得分:0)

尝试启用跟踪日志记录以获取有关映射所发生情况的更多详细信息:

RKLogConfigureByName("RestKit/ObjectMapping", RKLogLevelTrace);

那就是说,我不确定这是映射的问题。尝试从字符串对象中读取问题时抛出异常。 RestKit不应该根据您的用例来做这件事。因此,您需要在所有异常上添加断点,以便您可以看到完整的堆栈跟踪并找出正在发生的事情:Xcode adding an exception breakpoint

查看您的JSON和映射规范似乎没问题。