【发布时间】:2012-09-08 10:11:05
【问题描述】:
在我的应用程序中,我有一个表格视图。我想做的是: 通过网络获取数据,将它们存储在一个数组中,然后根据每个索引的值获取相应的行以获取背景。
我的意思是: 如果 data[0]=red---> 第 0 行的图像为红色,否则为绿色。
我已经设法下载了数据,但问题是首先分配了图像,然后发生了 http 请求。
例如: 这是我获取数据并将它们存储到数组的代码:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"connectionDidFinishLoading");
NSLog(@"Succeeded! Received %d bytes of data",[self.responseData length]);
// convert to JSON
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
colours== [NSMutableArray array];
NSString *parsed_data=[res objectForKey:@"data_1"];
NSLog(@"getting colour : %@",parsed_data);
[colours addObject:parsed_data];
.....
[self.mapMain reloadData];
}
mapMain 是我的 IBoutlet。 并用于设置背景:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier=@"SimpleTableCell";
//this is the identifier of the custom cell
SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSLog(@"Colour at %d is %@ ",indexPath.row,[colours objectAtIndex:indexPath.row]);
if ([@"red" isEqualToString:[colours objectAtIndex:indexPath.row]]) {
cell.mainImage.image = [UIImage imageNamed:[centersimages_red objectAtIndex:indexPath.row]];
} else{
cell.mainImage.image = [UIImage imageNamed:[centersimages_green objectAtIndex:indexPath.row]];
}
return cell;
}
其中 centerimages 是带有我的 .png 名称的表格。
这是我的日志:
Colour at 0 is (null)
Colour at 1 is (null)
....
didReceiveResponse
connectionDidFinishLoading
Succeeded! Received 287 bytes of data
getting colour for data : red
所以它首先将图像分配给单元格,然后执行请求。当然,我总是在 else 子句中看到图像。
我想先获取数据,然后分配图像。怎么做? 因为这是我的第一个 ios 应用程序,请完成答案或给我示例代码或提供教程链接。
编辑: 好的,我修复了那个拼写错误。现在我在尝试重新加载时收到 EXC_BAD_ACCESS 错误。如果我取消注释重新加载数据,则不会出现此错误。 请参阅我编辑的代码。我的表格视图已“连接”到 IBOutlet mainMap。
编辑2: 错误出现在这一行:
NSLog(@"Colour at %d is %@ ",indexPath.row,[colour objectAtIndex:indexPath.row]);
第二次(我的意思是当 cellForRowAtIndexPath 因为重新加载数据而被调用时)
错误是:EXC_BAD_ACCESS(代码 1)。 也许数组已发布或类似的东西?我应该检查什么?
【问题讨论】:
-
[tableView reloadData] 在您的请求完成后。
-
哪里 tableView 是我的 IBOutlet 的名称?
-
如果您的 tableView 作为 IBOutlet 连接到名为 tableView 的属性,那么它可能是
[self.tableView reloadData]。 -
我已将它放在我的 connectionDidFinishLoading 中,但没有任何改变。观看我编辑的代码。
-
这是什么:
colours== [NSMutableArray array];???它必须是这样的:colours = [NSMutableArray array];。注意单等号
标签: objective-c ios json uitableview