如何创建仅包含objective-c中的函数的文件?

时间:2023-01-02 20:00:57

I want to make a file that contains useful functions for my project. Well, I know that I can define a function inside my class implementation. But I don't really get it... I mean: I don't want to create a "class", just functions. Or are functions always part of a class? My objective-c knowledge is pretty limited, and my nice big book on objective-c does mention them, but does not explain how to implement them stand-alone.

我想创建一个包含项目有用功能的文件。好吧,我知道我可以在我的类实现中定义一个函数。但我真的不明白......我的意思是:我不想创建一个“类”,只是函数。或者函数总是属于一个类?我的客观知识非常有限,而且我关于objective-c的好大书确实提到了它们,但没有解释如何单独实现它们。

2 个解决方案

#1


Organize your code in plain old C style:

用普通的旧C风格组织你的代码:

  • a header file (.h) containing all function declarations.
  • 包含所有函数声明的头文件(.h)。

  • a body file (.c) containing all function bodies.
  • 包含所有函数体的正文文件(.c)。

Include your header file wherever you need one of your functions.

在您需要其中一个功能的地方包含头文件。

Let Xcode manage compilation and link.

让Xcode管理编译和链接。

#2


Because Objective-C is a superset of C, you can do this in the normal c way, in that you define your functions in a header file, which you include wherever you want to use them, then implement them in the .c file.

因为Objective-C是C的超集,所以你可以用普通的c方式做到这一点,因为你在头文件中定义你的函数,你可以在你想要使用它们的地方包含它们,然后在.c文件中实现它们。

I'd probably implement them as class methods on a class in order to namespace them, and prevent any accidental collisions, though.

我可能会将它们作为类方法在类上实现,以便命名它们,并防止任何意外冲突。

#1


Organize your code in plain old C style:

用普通的旧C风格组织你的代码:

  • a header file (.h) containing all function declarations.
  • 包含所有函数声明的头文件(.h)。

  • a body file (.c) containing all function bodies.
  • 包含所有函数体的正文文件(.c)。

Include your header file wherever you need one of your functions.

在您需要其中一个功能的地方包含头文件。

Let Xcode manage compilation and link.

让Xcode管理编译和链接。

#2


Because Objective-C is a superset of C, you can do this in the normal c way, in that you define your functions in a header file, which you include wherever you want to use them, then implement them in the .c file.

因为Objective-C是C的超集,所以你可以用普通的c方式做到这一点,因为你在头文件中定义你的函数,你可以在你想要使用它们的地方包含它们,然后在.c文件中实现它们。

I'd probably implement them as class methods on a class in order to namespace them, and prevent any accidental collisions, though.

我可能会将它们作为类方法在类上实现,以便命名它们,并防止任何意外冲突。