ios Objective-c 中的加号 (+) 与减号 (-)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10954049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
plus (+) versus minus (-) in objective-c
提问by SnowboardBruin
Possible Duplicate:
What do the plus and minus signs mean in Objective C next to a method?
What's the difference between using a plus or minus in Objective-C?
在 Objective-C 中使用加号或减号有什么区别?
For example, most of the time code starts -(void)somethingSomethingelse
, but sometimes it will be +(void)somethingSomethingelse
例如,大部分时间代码开始-(void)somethingSomethingelse
,但有时它会+(void)somethingSomethingelse
Thanks!
谢谢!
回答by Dima
-
functions are instance functions and +
functions are class (static) functions.
-
函数是实例函数,+
函数是类(静态)函数。
So let's say you have a class called Person
, and the following functions
因此,假设您有一个名为 的类Person
,以及以下函数
-(void)doSomething;
-(void)doSomething;
+(void)doSomethingElse;
+(void)doSomethingElse;
You would invoke these functions with the following:
您将使用以下命令调用这些函数:
Person *myPerson = [[Person alloc] init];
Person *myPerson = [[Person alloc] init];
[myPerson doSomething];
[myPerson doSomething];
[Person doSomethingElse];
[Person doSomethingElse];
This is more of a syntax description, assuming you understand the concept of class vs instance.
这更多是一种语法描述,假设您了解类与实例的概念。
edit:
编辑:
just to add: In objective-C, you can actually invoke a class function on an instance, but the effect is no different than invoking it on the class itself (essentially compiles to the same thing).
补充一点:在objective-C 中,您实际上可以在实例上调用类函数,但效果与在类本身上调用它没有什么不同(基本上编译为相同的东西)。
So you can do
所以你可以做
[myPerson doSomethingElse]
[myPerson doSomethingElse]
Generally, you wouldn't do this as it is confusing and misleading to read. I am pointing it out so you won't be surprised if you come across code like this somewhere.
通常,您不会这样做,因为它会使阅读产生混淆和误导。我指出了这一点,所以如果您在某处遇到这样的代码,您不会感到惊讶。
回答by Scott Bossak
In short, (+) is a class method and (-) is an instance method
简而言之,(+) 是类方法,(-) 是实例方法
See this answer for a full explanation What is the difference between class and instance methods?
有关完整说明,请参阅此答案 类和实例方法之间有什么区别?
回答by Nico
member and public functions respectively.
分别是成员函数和公共函数。
Such that
这样的
id object = [[NSObject alloc] init];
+ (id)alloc;
- (id)init;
Where NSObject is a Class and id is an object
其中 NSObject 是一个类,id 是一个对象
If you have ever used C++, a + is equivalent to static
如果你曾经使用过 C++,a + 就相当于 static