我正在尝试将字段“field_message_subject”和“field_message_body”中的JSON数据拖到我应用中的表格单元格中。我正在使用以下代码来执行此操作,并且数据已成功返回,但我的应用程序崩溃且标签未填充。崩溃错误是:
由于未捕获的异常'NSRangeException'而终止应用程序,原因: '*** - [__ NSArrayM objectAtIndex:]:索引1超出界限[0 .. 0]'
Viewcontroller.m
- (void)viewDidLoad {
[super viewDidLoad];
NSDictionary *entityData = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"1"] forKey:@"uid"];
[DIOSEntity
entityGet:entityData
name:@"entity_message"
eid:@"uid"
success:^(AFHTTPRequestOperation *op, id response) {
self.messages = [NSMutableArray arrayWithObject:(NSDictionary*)response];
dispatch_async(dispatch_get_main_queue(), ^(void){
[self.tableView reloadData];
});
}
failure:^(AFHTTPRequestOperation *op, NSError *err) { NSLog(@"failed to get data"); }
];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *PointsTableIdentifier = @"MyMessagesCell";
MyMessagesCell *cell = (MyMessagesCell *)[tableView dequeueReusableCellWithIdentifier:PointsTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyMessagesCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSDictionary *receivedSubjectLine = [self.messages objectAtIndex:indexPath.row];
[[cell subjectLine] setText:[receivedSubjectLine objectForKey:@"field_message_subject"]];
NSLog(@"Received message subject is here %@", receivedSubjectLine);
return cell;
}
请参阅下面返回的JSON格式:
2016-02-02 10:37:19.996 app[4208:1406692] Messages are as follows (
{
arguments = (
);
data = (
);
"field_message_body" = {
und = (
{
format = "<null>";
"safe_value" = "Testing message center";
value = "Testing message center";
}
);
};
"field_message_group_ref" = (
);
"field_message_subject" = {
und = (
{
format = "<null>";
"safe_value" = Testing;
value = Testing;
}
);
};
"field_message_user_ref" = (
);
language = en;
mid = 1;
"rdf_mapping" = (
);
timestamp = 1447260780;
type = "private_message";
uid = 1;
}
)
答案 0 :(得分:1)
tableview应该知道它需要多少个单元格。 定义此tableviewdatasource方法以设置所需的行数。
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.messages count];
}
顺便说一下,如果你增加行数,你应该在viewDidLoad
中初始化self.messages并添加条目{h} {/ p>
addObject:
因为这将始终为您的数组分配新空间,其大小始终为1。
修改强>
self.messages = [NSMutableArray arrayWithObject:(NSDictionary*)response];
在字段 NSDictionary *receivedSubjectLine = [self.messages objectAtIndex:indexPath.row];
NSArray * val = receivedSubjectLine[@"und"];
NSString *textToWrite = val[0][@"value"];
[cell.subjectLine setText:textToWrite];
答案 1 :(得分:1)
根据您的JSON格式,访问field_message_subject应该类似于
[[[[receivedSubjectLine objectForKey:@"field_message_subject"] objectForKey:@"und"] objectAtIndex:0] objectForKey:@"value"];
答案 2 :(得分:0)
您要将response
(NSDictionary
)添加到self.messages
。您在代码中的其他位置插入self.messages
。因此messages
数组将始终包含一个值。您正尝试从messages
数组获取行索引处的对象。因此,如果行数超过1,您的应用程序将崩溃,因为messages
只包含一个对象。