views:

110

answers:

1

Hello Everyone,

What is the difference between "+" and "-" before the function name interface declaration in an Objective-C program. Example:

- (void)continueSpeaking;

+ (NSArray *)availableVoices;

What's the difference?

+6  A: 

+ defines a class method

Class methods belong to the class itself, not instances of the class.

Example: [ AppDelegate someMethod ] //someMethod is a class method

- defines an instance method

Example [ [ [ UIApplication sharedApplication ] delegate ] someMethod ] // someMethod is an instance method

The best way to describe the difference is that - methods operate on objects, while + methods operate on the class itself.

Say your class was named MyClass, and you created an instance of it by calling alloc/init, and stored it in a variable called myInstance:

- (void)continueSpeaking can be called like this: [ myInstance continueSpeaking ].

However, this method + (NSArray *)availableVoices can only be called like this: [ MyClass availableVoices ].

Jacob Relkin
You're thinking of Java. They are called _class methods_ in Objective-C, and there is a `self` in a class method — `self` is the class. So for example, if your class has the methods `+[MyClass someMethod]` and `+[MyClass someOtherMethod]`, you could call `[self someOtherMethod]` from within `someMethod`.
Chuck
Note that the standard `alloc` is a class method that returns an instance, while `init` is an instance method.
outis