【问题标题】:Objective-C How do I return a struct datatype?Objective-C 如何返回结构数据类型?
【发布时间】:2013-03-02 14:44:06
【问题描述】:
struct Line {

    NSUInteger x1;
    NSUInteger x2;
};

// ...

- (Line)visibleLine;

上面的代码显然不起作用,因为 Line 不是有效的类型。有什么建议吗?

【问题讨论】:

    标签: objective-c


    【解决方案1】:

    Objective-C 是基于 C 而不是 C++。在C 中我们需要使用struct Line,而在C++ 中Line 很好。

    你可以这样做:

    struct {
        NSUInteger x1;
        NSUInteger x2;
    } Line;
    
    // ...
    
    - (struct Line)visibleLine{
        
    }
    

    struct Line {
        NSUInteger x1;
        NSUInteger x2;
    };
    typedef struct Line Line;
    
    // ...
    
    - (Line)visibleLine;
    

    以上是大多数 C 框架的首选。

    还有,

    typedef struct {
        NSUInteger x1;
        NSUInteger x2;
    } Line;
    
    // ...
    
    - (Line)visibleLine;
    

    【讨论】:

      【解决方案2】:
      typedef struct {
          NSUInteger x1;
          NSUInteger x2;
      } Line;
      
      // ...
      
      - (Line)visibleLine;
      

      我最初(在其他答案之前)出于明确的原因提出上述建议:这就是 Apple 在自己的代码中的做法。这不是唯一的方式,但它是 Apple 的标准方式。它从不将 struct 放在其 API 中任何位置的方法原型中。

      【讨论】:

        【解决方案3】:

        C 中,struct LineLine 是不同的。您需要别名 struct Line 以仅使用 Line 引用它。所以,

        struct Line { /* ... */ };        // Make a struct.
        
        typedef struct Line       Line;   // Make an alias.
        

        这也可以一次写完。

        typedef struct Line { /* ... */ }        Line;
        

        C++ 自动生成别名,但您应该将 C++ 视为与 C 完全不同的语言。不要对他们的名字感到困惑。

        【讨论】:

          【解决方案4】:

          你错过了关键字struct

          - (struct Line)visibleLine;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2010-10-19
            • 1970-01-01
            • 2014-06-03
            • 2019-06-21
            • 1970-01-01
            • 1970-01-01
            • 2016-01-19
            • 2022-01-04
            相关资源
            最近更新 更多