how to return multiple values from a method

試著忘記壹切 提交于 2019-12-09 16:53:08

问题


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) addressLocation{
 - --------
 ----------
 return location;
 }

is it possible to return multiple locations (I mean return location1 , return location2 . . ..) ?? please help me thanks


回答1:


Add your location objects to an array and return the array instead. e.g.

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



回答2:


CLLocationCoordinate2D is not an object so they can not just be added to an array and returned. 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
  2. malloc a new struct pointer, copy the data, then store the pointer in an NSValue
  3. Create a class that has the same properties as the fields of the struct, and add that to an array

Option 1 and 2 require additional memory management as to when to free the data so avoid those. Option 3 is good and it just so happens MapKit offers the class CLLocation. Here is an example of 2 coordinates.

-(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;
}


来源:https://stackoverflow.com/questions/6538726/how-to-return-multiple-values-from-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!