method with 2 return values

后端 未结 7 814
春和景丽
春和景丽 2021-01-24 15:48

I want to call a method which returns two values

basically lets say my method is like the below (want to return 2 values)

NSString* myfunc
{
   NSString          


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-24 16:00

    As you can only return one value/object, maybe wrap them up in an array:

    -(NSArray*) arrayFromMyFunc
    {
       NSString *myString = @"MYDATA";
       NSString *myString2 = @"MYDATA2";
       return [NSArray arrayWithObjects:myString,myString2,nil];
    }
    

    You can then use it like this:

    NSArray *arr = [self arrayFromMyFunc];
    
    NSString *value1 = [arr objectAtIndex:0];
    NSString *value2 = [arr objectAtIndex:1];
    

    You could pass results back by reference, but this is easy to get wrong (syntactically, semantically, and from memory management point of view).

    Edit One more thing: Make sure that you really need two return values. If they are quite independent, two separate function are often the better choice - better reusabilty and mentainable. Just in case you are making this as a matter of premature optimization. :-)

提交回复
热议问题