-1

Possible Duplicate:
What do the plus and minus signs mean in Objective C next to a method?

Since I have started programming in Objective C, I have been implementing methods like this:

-(void)doSomething

Recently, I saw this in a piece of source code:

+(void)doSomething

What is the difference between the + and the - and what is the +?

Community
  • 1
  • 1
CoreCode
  • 2,227
  • 4
  • 22
  • 24

2 Answers2

4

The methods beginning with + are class methods; that is, they're not called on actual objects (instances of a class), but rather on a class itself.

  • So what is the difference if calling it on the class itself rather than the object? – CoreCode May 06 '12 at 04:01
  • 1
    @CoreCode you can't call the instance methods on the class. You need an instance of the class in order to use those methods. – Stefan H May 06 '12 at 04:02
  • Instance methods are called on an object; that is, they can behave differently for each instance of the same class when the data structures' values in the two instances are different. But a class method will always do the same sort of thing (for the same arguments given, and if no static variables related to that methods are modified) when called on one particular class. –  May 06 '12 at 04:04
  • @H2CO3 that last sentence is incorrect. If the class method modifies a static field, you might not get the same results on every execution of the method, even with the same parameters. – Stefan H May 06 '12 at 04:08
  • 2
    Just for technical correctness, I'll point out that classes *are* "actual objects". They are instances of their metaclasses. In fact, that's really the meaning of a class method – it's an instance method of the class's metaclass. (Not that a newbie needs to know all this, but still.) – Ken Thomases May 06 '12 at 04:31
  • Yes, this is technically correct, however it is a speciality of Objective-C tha one can simply cast (Class) to (id) due to their similar memory layout (both structs begin with Class isa; (or metaclass). In most traditional OO languages, such as C", however, the classes are not instances, and class methods are called "static" methods. –  May 06 '12 at 04:33
0

The methods with "+" before return type indicates that there are such an static methods (it exists without the instantiation of an object of that class). The methods with "-" are related to individual objects.

echristopherson
  • 6,974
  • 2
  • 21
  • 31
innuendoreplay
  • 125
  • 1
  • 7