【问题标题】:Functions / Methods in Objective C!Objective C 中的函数/方法!
【发布时间】:2010-10-07 17:55:49
【问题描述】:

我需要目标 C 中的函数方面的帮助?

在 C++ 中,我可以创建这样的函数:

int testFunction(int zahl) { 
    int loop;
    loop = zahl * 10;
    return loop;
}

这个函数将我的 zahl 乘以 10 并返回结果。在 C++ 中,我可以随时调用此函数:

testFunction(5);

它返回 50。

我不明白如何在目标 c 中制作像 testFunction 这样的函数?我要这样做吗

-(void)testFunction{}?

非常感谢您的帮助!

Greez Franhu

【问题讨论】:

    标签: c++ objective-c function methods


    【解决方案1】:

    随便用

    int testFunction(int zahl)
    {
        return zahl * 10;
    }
    

    如果你想声明成员函数,你只需要其他符号(参见 user467105 的回答)。

    【讨论】:

      【解决方案2】:

      在Objective-C中,函数可以这样写:

      -(int)testFunction:(int)zahl
      {
          int loop; 
          loop = zahl * 10;   
          return loop; 
      }
      

      并像这样调用:

      int testResult = [self testFunction:5];
      //assuming testFunction is in same class as current (ie. self)
      

      但是,我相信至少在 Cocoa 中,您可以同时拥有 C++ 和 Objective-C 代码,因此您可以按原样包含 C++ 版本并从 Objective-C 代码中调用它。

      【讨论】:

      • 你描述的是一个Objective-C 方法,而不是一个函数。
      • 非常感谢您的回复。是的,我不明白函数和方法之间的区别?
      【解决方案3】:

      你所拥有的函数在 Objective-C 中的工作方式完全相同:

      int testFunction(int zahl) { 
          int loop;
          loop = zahl * 10;
          return loop;
      }
      

      你有的其他语法:

      -(void)testFunction{}?

      是一个方法,在你需要的.h文件中:

      @interface SomeClass : NSObject {
      }
      
      -(int)testFunction:(int)zahl;
      

      @结束

      在你的 .m 中:

      -(int)testFunction:(int)zahl {
          int loop;
          loop = zahl * 10;
          return loop;
      }
      

      那你可以叫它[someObjectOfTypeSomeClass testFunction:13]

      方法适用于您的对象。使用方法来改变或查询对象的状态。使用函数来做其他事情。 (这和C++的方法和函数一样)

      【讨论】:

      • 谢谢!现在我可以继续... ;-)
      猜你喜欢
      • 2011-06-18
      • 2013-12-23
      • 1970-01-01
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      • 2010-11-06
      • 2013-05-27
      相关资源
      最近更新 更多