Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 328
smartsanja Avatar asked Jun 30 '11 17:06

smartsanja


People also ask

Can you return multiple variables in one method?

You cannot explicitly return two variables from a single function, but there are various ways you could concatenate the two variables in order to return them.

Can a method return multiple values in Python?

You can return multiple values from a function in Python. To do so, return a data structure that contains multiple values, like a list containing the number of miles to run each week. Data structures in Python are used to store collections of data, which can be returned from functions.


2 Answers

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;
}
like image 195
Joe Avatar answered Oct 23 '22 07:10

Joe


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.
}
like image 28
George Johnston Avatar answered Oct 23 '22 07:10

George Johnston