私のアプリでは、テーブルビューがあります。私がやりたいことはこれです:Web経由でデータを取得し、それらを配列に保存してから、各インデックスの値に応じて、対応する行を背景に取得します。
つまり、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 は、私の .pngs 名を持つテーブルです。
これは私のログです:
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 アプリなので、回答を完了するか、サンプル コードを提供するか、チュートリアルへのリンクを提供してください。
EDIT:OK私はそのタイプミスを修正しました。そして、リロードしようとすると EXC_BAD_ACCESS エラーが発生します。リロード データのコメントを外すと、このエラーは表示されません。編集したコードを参照してください。テーブル ビューは IBOutlet mainMap に「接続」されています。
EDIT2:エラーは次の行にあります:
NSLog(@"Colour at %d is %@ ",indexPath.row,[colour objectAtIndex:indexPath.row]);
2回目(データのリロードのためにcellForRowAtIndexPathが呼び出されたときを意味します)
エラー: EXC_BAD_ACCESS (コード 1)。たぶん、配列が解放されるか、このようなものですか?そのために何をチェックすればよいですか?