简体   繁体   English

如何从一个方法返回多个值

[英]how to return multiple values from a method

I have -(CLLocationCoordinate2D) method, I want to return multiple locations from that method (those locations are using in another method) my method looks like this,我有 -(CLLocationCoordinate2D) 方法,我想从该方法返回多个位置(这些位置在另一个方法中使用)我的方法看起来像这样,

-(CLLocationCoordinate2D) addressLocation{
 - --------
 ----------
 return location;
 }

is it possible to return multiple locations (I mean return location1, return location2. . ..)??是否可以返回多个位置(我的意思是返回位置 1,返回位置 2 ......)? please help me thanks请帮帮我谢谢

CLLocationCoordinate2D is not an object so they can not just be added to an array and returned. CLLocationCoordinate2D 不是 object 因此它们不能仅仅添加到数组中并返回。 Since they are structs there are a few options,由于它们是结构,因此有几个选项,

  1. malloc an array the old fashion way and copy the struct data into the array malloc一个数组旧时尚方式并将结构数据复制到数组中
  2. malloc a new struct pointer, copy the data, then store the pointer in an NSValue malloc一个新的结构指针,复制数据,然后将指针存储在一个NSValue
  3. Create a class that has the same properties as the fields of the struct, and add that to an array创建一个与结构的字段具有相同属性的 class,并将其添加到数组中

Option 1 and 2 require additional memory management as to when to free the data so avoid those.选项 1 和 2 需要额外的 memory 管理来确定何时释放数据,因此请避免使用这些。 Option 3 is good and it just so happens MapKit offers the class CLLocation .选项 3 很好,恰巧 MapKit 提供了 class CLLocation Here is an example of 2 coordinates.这是 2 个坐标的示例。

-(NSArray*) addressLocations
{
    CLLocationCoordinate2D coord1 = CLLocationCoordinate2DMake(1.00, 1.00);
    CLLocationCoordinate2D coord2 = CLLocationCoordinate2DMake(2.00, 2.00);

    CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:coord1.latitude longitude:coord1.longitude];
    CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:coord2.latitude longitude:coord2.longitude];

    NSArray *array = [NSArray arrayWithObjects:loc1, loc2, nil];

    [loc1 release];
    [loc2 release];

    return array;
}

Add your location objects to an array and return the array instead.将您的位置对象添加到数组并返回该数组。 eg例如

-(NSArray*) addressLocation{
   ...  // Set your locations up
   NSArray *array = [NSArray arrayWithObjects:location1, location2, nil];
   ... // Do any additional processing and return array.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM