【问题标题】:get multiple output from a single method in Objective-c从 Objective-c 中的单个方法获取多个输出
【发布时间】:2012-08-06 02:12:51
【问题描述】:

我有自己的类,正在编写一个具有多个输入(三个浮点值)和多个输出(三个浮点值)的方法。我不知道如何从一个方法中获得多个输出。有任何想法吗?

我目前的方法是这样的:

- (void)convertABC2XYZA:(float)a
                  B:(float)b 
                  C:(float)c 
            outputX:(float)x 
            outputY:(float)y 
            outputZ:(float)z 
{
    x = 3*a + b;
    y = 2*b;
    z = a*b + 4*c;
}

【问题讨论】:

    标签: objective-c methods


    【解决方案1】:

    “返回”多个输出的一种方法是将指针作为参数传递。像这样定义你的方法:

    - (void)convertA:(float)a B:(float)b C:(float) intoX:(float *)xOut Y:(float *)yOut Z:(float)zOut {
        *xOut = 3*a + b;
        *yOut = 2*b;
        *zOut = a*b + 4*c;
    }
    

    然后这样称呼它:

    float x, y, z;
    [self convertA:a B:b C:c intoX:&x Y:&y Z:&z];
    

    另一种方法是创建一个结构并返回它:

    struct XYZ {
        float x, y, z;
    };
    
    - (struct XYZ)xyzWithA:(float)a B:(float)b C:(float)c {
        struct XYZ xyz;
        xyz.x = 3*a + b;
        xyz.y = 2*b;
        xyz.z = a*b + 4*c;
        return xyz;
    }
    

    这样称呼它:

    struct XYZ output = [self xyzWithA:a B:b C:c];
    

    【讨论】:

      【解决方案2】:

      Objective-C 中的方法(不像 Python or JavaScript)最多只能返回 1 个东西。创建一个“事物”以包含您要返回的 3 个浮点数,然后返回其中一个。

      您可以使用output parameters,而不是返回。

      【讨论】:

        【解决方案3】:

        这与 C 的关系比与 Objective-c 的关系更大。

        您需要通过引用传递值。你的函数应该这样声明:

        - (void)convertABC2XYZA:(float)a
                      B:(float)b 
                      C:(float)c 
                outputX:(float *)x 
                outputY:(float *)y 
                outputZ:(float *)z;
        

        并像这样调用:

        [receiver convertABC2XYZA:a B:b C:c outputX:&x outputY:&y outputZ:&z];
        

        【讨论】:

          猜你喜欢
          • 2018-06-03
          • 2010-12-14
          • 2015-12-04
          • 2011-11-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-11-12
          • 1970-01-01
          相关资源
          最近更新 更多