2

iOSのsqlitedbから入力されたmutablearrayがあります。正しくロードして表示するための注釈を取得しました。私の質問は、配列のサイズで注釈を追加するループをどのように作成できるかです。次のコードを試し、配列の最後のエントリを取得して表示しました

NSMutableArray *annotations=[[NSMutableArray alloc] init];
CLLocationCoordinate2D theCoordinate5;
MyAnnotation* myAnnotation5=[[MyAnnotation alloc] init];
for (int i = 0; i < _getDBInfo.count; i++) {

    dbInfo *entity = [_getDBInfo objectAtIndex:i];

    NSNumber *numlat=[[NSNumber alloc] initWithDouble:[entity.Latitude doubleValue]];
    NSNumber *numlon=[[NSNumber alloc] initWithDouble:[entity.Longitude doubleValue]];
    NSLog(@"%d",[_getDBInfo count]);
    la=[numlat doubleValue];
    lo=[numlon doubleValue];
    theCoordinate5.latitude=la;
    theCoordinate5.longitude=lo;

    myAnnotation5.coordinate=theCoordinate5;
    myAnnotation5.title=[NSString stringWithFormat:@"%@"entity.EntityNo];
    myAnnotation5.subtitle=[NSString stringWithFormat:@"%@",entity.EntityName]; 
    [mapView addAnnotation:myAnnotation5];
    [annotations addObject:myAnnotation5];
}

私の質問は、配列のカウントに基づいてビュー注釈オブジェクトを作成して追加するにはどうすればよいかということだと思います。

どんな助けでも大歓迎です。

私はiOSとプログラミングに不慣れなので、優しくしてください。

4

2 に答える 2

3

myAnnotation5オブジェクトは1つだけです。coordinate、などを設定titleすると、そのインスタンスに設定されますが、これはたまたまannotations複数回追加されています。したがって、のすべてのエントリにannotationsは、最後に設定したプロパティのセットがあります。これは、のすべてのエントリannotationsが実際には同じオブジェクトであるためです。

myAnnotation5これを修正するには、ループの反復ごとにオブジェクトを新たに作成する必要があります。

for (int i = 0; i < _getDBInfo.count; i++) {
    MyAnnotation* myAnnotation5=[[MyAnnotation alloc] init];
    ...
    myAnnotation5.coordinate=theCoordinate5;
    myAnnotation5.title=[NSString stringWithFormat:@"%@", entity.EntityNo];
    myAnnotation5.subtitle=[NSString stringWithFormat:@"%@", entity.EntityName];
    ...
    [mapView addAnnotation:myAnnotation5];
}

2つの傍白:

  1. ARCを使用してビルドしているといいのですが、そうでない場合は、メモリが左右にリークしています。
  2. MKMapViewにはプロパティがあるため、独自の配列-annotationsを保持する理由はほとんどありません。への参照を保持するだけです。annotationsmapView
于 2012-05-14T17:23:51.517 に答える
1

この行を移動します:

MyAnnotation* myAnnotation5=[[MyAnnotation alloc] init];

プロパティをに設定する直前にforループの内側に移動しますmyAnnotation5

現在のように、オブジェクトを1つだけ作成しMyAnnotation、そのプロパティを繰り返し変更しています。

于 2012-05-14T17:22:44.297 に答える