0

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

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

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

- (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];
}

这是我的问题.h:

#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/"
}

美味的 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”而终止应用程序,原因:“[<__NSCFString 0x76b3030> valueForUndefinedKey:]:此类不符合关键问题的关键值编码。”

我阅读了https://github.com/RestKit/RestKit/wiki/Object-Mapping但没有发现我做错了什么。

我的课有什么问题?

4

1 回答 1

0

尝试打开跟踪日志以获取有关映射发生情况的更多详细信息:

RKLogConfigureByName("RestKit/ObjectMapping", RKLogLevelTrace);

也就是说,我不确定这是映射的问题。尝试从字符串对象读取问题时引发异常。RestKit 不应该根据您的用例这样做。因此,您需要在所有异常上添加断点,以便查看完整的堆栈跟踪并弄清楚发生了什么:Xcode 添加异常断点

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

于 2013-04-30T12:40:56.833 回答