method with 2 return values

后端 未结 7 723
春和景丽
春和景丽 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:01

    You can only return 1 value. That value can be a struct or an object or a simple type. If you return a struct or object it can contain multiple values.

    The other way to return multiple values is with out parameters. Pass by reference or pointer in C.

    Here is a code snippet showing how you could return a struct containing two NSStrings:

    typedef struct {
        NSString* str1;
        NSString* str2;
    } TwoStrings;
    
    TwoStrings myfunc(void) {
        TwoStrings result;
        result.str1 = @"data";
        result.str2 = @"more";
        return result;
    }
    

    And call it like this:

    TwoStrings twoStrs = myfunc();
    NSLog(@"str1 = %@, str2 = %@", twoStrs.str1, twoStrs.str2);
    

    You need to be careful with memory management when returning pointers even if they are wrapped inside a struct. In Objective-C the convention is that functions return autoreleased objects (unless the method name starts with create/new/alloc/copy).

提交回复
热议问题