如何访问这个数组的元素(iOS objective-C)?

时间:2017-03-16 15:31:59

标签: objective-c

我定义了以下数组:

NSArray *array = @[[NSNumber numberWithFloat:coordinate.latitude], [NSNumber numberWithFloat:coordinate.longitude]];
[tappedCoordinates addObject:array];

这是一个多维数组(每个元素有2个条目)。我如何检索数组中每个元素的第一个和第二个条目?

5 个答案:

答案 0 :(得分:2)

为什么不将坐标包裹在NSValue中?有一种专门的方法:

NSValue *value = [NSValue valueWithMKCoordinate:coordinate];
[tappedCoordinates addObject: value];

要恢复坐标:

NSValue *value = array[0];
CLLocationCoordinate2D coordinate = [value MKCoordinateValue];
CLLocationDegrees latitude = coordinate.latitude;
CLLocationDegrees longitude = coordinate.longitude;

重要提示:要使用此API,您需要导入MapKit

答案 1 :(得分:1)

试试这个:

  NSLog(@"%@",[[tappedCoordinates objectAtIndex:0] objectAtIndex:0]);   
  NSLog(@"%@",[[tappedCoordinates objectAtIndex:0] objectAtIndex:1]); 
    //This will print NSNumber object from which you can get lat and lang

OR

 NSLog(@"%@",tappedCoordinates[0][0]);
  NSLog(@"%@",tappedCoordinates[0][1]);//Take care about conversion back to coordinate from NSNumber.

for for loop

for(int i=0;i< tappedCoordinates.count;i++){
    for(int j=0; j<[[tappedCoordinates objectAtIndex:i] count];j++){
       NSLog(@"%@",tappedCoordinates[i][j]);
    }
}

答案 2 :(得分:1)

要获得数组的第一个元素,请尝试以下方法:

 NSArray *array = [tappedCoordinates objectAtIndex:0]; 

读取第一个数组数组的元素:

  NSLog(@"%@",[array objectAtIndex:0]);   
  NSLog(@"%@",[array objectAtIndex:0]); 

OR

  NSLog(@"%@",[[tappedCoordinates objectAtIndex:0] objectAtIndex:0]);   
  NSLog(@"%@",[[tappedCoordinates objectAtIndex:0] objectAtIndex:1]); 

回答你的意见(预期):

CLLocationCoordinate2D position;
for (int i = 0; i <= [tappedCoordinates count]-1; i++)
{
    position.latitude = [[[tappedCoordinates objectAtIndex:i] objectAtIndex:0] floatValue];
    position.longitude = [[[tappedCoordinates objectAtIndex:i] objectAtIndex:1] floatValue];
    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = position;
    marker.map = _mapView;
}

答案 3 :(得分:0)

如果你想要实现的是一个简单的点击CGPoints数组。你可以试着写

[tappedCoordinates addObject [NSValue valueWithCGPoint:CGPointMake(coordinate.latitude, coordinate.longitude)]]

然后得到一个值:

//or get any other position from the array :D
NSValue *value = [tappedCoordinates firstObject];

CGPoint coordinate = [value CGPointValue];

答案 4 :(得分:0)

将数组中的纬度和经度值保存为此

NSMutableArray *tappedCoordinates =[[NSMutableArray alloc]init];
NSDictionary *dict =  @{
  @"latitude" : [NSNumber numberWithFloat:coordinate.latitude],
  @"longitude" : [NSNumber numberWithFloat:coordinate.longitude],
 };

[tappedCoordinates addObject:dict];

NSLog(@"latitude is---%@",[[tappedCoordinates objectAtIndex:0]objectForKey:@"latitude"]);
NSLog(@"longitude is---%@",[[tappedCoordinates objectAtIndex:0]objectForKey:@"longitude"]);