编辑 - 解决: 我为“Feed”添加了一个模型,它处理了我遇到的映射问题。谢谢!
我想在UITableView
行中显示所有“标题”,但我遇到了崩溃:
WebListViewController.m -
@interface WebListViewController ()
@property (strong, nonatomic) NSArray *headlinesNow;
@end
@implementation WebListViewController
@synthesize tableView = _tableView;
@synthesize headlinesNow;
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *lAbbreviation = [defaults objectForKey:@"lAbbreviation1"];
NSString *tID = [defaults objectForKey:@"tId1"];
NSString *url = [NSString stringWithFormat:@"/now/?l=%@&t=%@&apikey=5xxxxxxxx", lAbbreviation, tID];
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:url usingBlock:^(RKObjectLoader *loader) {
loader.onDidLoadObjects = ^(NSArray *objects) {
headlinesNow = objects;
[_tableView reloadData];
[loader.mappingProvider setMapping:[Headline mapping] forKeyPath:@"feed.headline"];
loader.onDidLoadResponse = ^(RKResponse *response){
NSLog(@"BodyAsString: %@", [response bodyAsString]);
};
}];
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return headlinesNow.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"standardCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Headline *headlineLocal = [headlinesNow objectAtIndex:indexPath.row];
NSString *headlineText = [NSString stringWithFormat:@"%@", headlineLocal.headline];
cell.textLabel.text = headlineText;
return cell;
}
Headline.h
@interface Headline : NSObject
@property (strong, nonatomic) NSString *headline;
@property (strong, nonatomic) Links *linksHeadline;
+ (RKObjectMapping *) mapping;
@end
Headline.m
@implementation Headline
+ (RKObjectMapping *)mapping {
RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:[self class] usingBlock:^(RKObjectMapping *mapping) {
[mapping mapKeyPathsToAttributes:
@"headline", @"headline",
nil];
[mapping hasOne:@"links" withMapping:[Links mapping]];
}];
return objectMapping;
}
@end
JSON Response Body -
{
"timestamp": "2013-05-03T22:03:45Z",
"resultsOffset": 0,
"status": "success",
"resultsLimit": 10,
"breakingNews": [],
"resultsCount": 341,
"feed": [{
"headline": "This is the first headline",
"lastModified": "2013-05-03T21:33:32Z",
"premium": false,
"links": {
"api": {
我收到了NSLog
的{{1}}输出,但程序崩溃了,没有填写bodyAsResponse
。我显然没有正确导航到JSON?有什么想法吗?
感谢您的帮助,如果您需要更多代码段,请与我们联系 -
修改 - 崩溃是: 由于未捕获的异常'NSUnknownKeyException'而终止应用程序,原因:'[< __ NSCFString 0xe693110> valueForUndefinedKey:]:此类不是关键标题的键值编码兼容。'
答案 0 :(得分:1)
第一个问题是您当前的forKeyPath:@"feed.headline"
。它应该只是forKeyPath:@"feed"
,因为该密钥路径对您的JSON无效。原因是JSON中的feed
是一个数组,因此它应映射到您的Headline
对象,然后该对象的映射定义将用于headline
。
下一期是linksHeadline
属性和[mapping hasOne:@"links" withMapping:[Links mapping]];
。键名不匹配。将Headline
中的媒体资源名称更改为links
。