0

こんにちは、for ループを使用して NSMutableDictionary に 2 つの NSMutableArray データを入力しようとしましたが、ループが終了すると、NSMutableDictionary は最後にロードされた値のみを表示します。コードに従ってください

 -(void)calculateDistance
{
    self.distanceArray=[[NSMutableArray alloc]init];
    self.dict=[[NSMutableDictionary alloc]init];



    for (int i=0; i<[self.nombre count]; i++) {


       CLLocation *shopPosition=[[CLLocation alloc]initWithLatitude:[[self.latitud objectAtIndex:i] floatValue]longitude:[[self.longitud objectAtIndex:i]floatValue]];
        self.userPosition=[[CLLocation alloc]initWithLatitude:self.currentLat longitude:self.currentLong];

        self.distance=[shopPosition distanceFromLocation:self.userPosition];

       [self.distanceArray addObject:[NSNumber numberWithFloat:self.distance]];

        [self.dict setObject:[self.distanceArray objectAtIndex:i] forKey:@"distance"];
        [self.dict setObject:[self.nombre objectAtIndex:i]  forKey:@"nombre"];


   }

    NSLog(@" DICT %@",self.dict);

どうもありがとう

4

2 に答える 2

2

新しい値を常に同じキーに設定します。

[self.dict setObject:[self.distanceArray objectAtIndex:i] forKey:@"distance"];
[self.dict setObject:[self.nombre objectAtIndex:i]  forKey:@"nombre"];

代わりに NSMutableArray を使用し、ループ サイクルごとに新しい NSDictionary を追加する必要があります。

    NSDictionary *dict = @{@"distance" : self.distanceArray[i],
                           @"nombre"   : self.nombre[i]
   };

    [self.newMutArray addObject: dict];
于 2013-07-03T14:03:05.037 に答える
1
[self.dict setObject:[self.distanceArray objectAtIndex:i] forKey:@"distance"];
[self.dict setObject:[self.nombre objectAtIndex:i]  forKey:@"nombre"];

この 2 行が問題です。nombre新しいまたは新しいを取得するたびに、distanceArrayそれを同じキーに保存していますNSDictionary

したがって、最終的にあなたのNSDictionary意志には「距離」と「ノンブル」の 2 つの鍵しかありません。

NSMutableArrayオブジェクトのを作成する必要があるかもしれませんNSDictionary。それ以外の場合は、ディクショナリ内のオブジェクトごとに、keys:"nombre1"、"nombre2" などのような複数のキーを作成する必要があります。

NSMutableArrayその中にi NSDictionaryオブジェクトを入れて を作ってみてください。このような:

[array addObject:[NSDictionary dictionaryWithObjectsAndKeys:[self.distanceArray objectAtIndex:i],@"distance",[self.nombre objectAtIndex:i],@"nombre"]];

次に、最終的なarrayオブジェクトにはi NSDictionary、それぞれが名前と距離キーを含むオブジェクトがあります。

インデックスで名前と距離にアクセスするには、n次を使用します。

nombre = [[array objectAtIndex:n] objectForKey:@"nombre"];
distance = [[array objectAtIndex:n] objectForKey:@"distance"];
于 2013-07-03T14:10:27.177 に答える