Matej
Matej

Reputation: 9805

What is the difference between + and - when defining a property of method?

and the - and + signs in front of a declaration of property and method confuses me a lot. Is there a difference if I declare the method this way:

- (void)methodName:(id)sender {}

and this way

+ (void)methodName:(id)sender {}

I really don't get it.

Upvotes: 1

Views: 152

Answers (3)

No One in Particular
No One in Particular

Reputation: 2894

To embelish on @Tommy's answer, the (-)methods will have the use of a 'self' variable which is the class instance that the method will work on. The (+) methods won't have that.

For example, if you had a class FooBar and you wanted to compare 2 instances, you could do either of the following:

+ (BOOL) compare:(FooBar)fb1 and:(FooBar)fb2 {
        // compare fb1 and fb2
        // return YES or NO
}

or

- (BOOL) compare:(FooBar)fb2
        // compare self and fb2
        // return YES or NO
}

The second routine has the 'self' variable which is similar to the fb1 in the first routine. (These routines are contrived, but I hope you get the picture.)

Upvotes: 1

nekno
nekno

Reputation: 19267

- (void)methodName:(id)sender {}

is an instance method, meaning you create an instance of a class, and can call the method on the object, or in Objective-C parlance, send a message to the object selector.

+ (void)methodName:(id)sender {}

is a class method, meaning it is a static method you call on the class itself, without first instantiating an object.

In the following example, alloc and stringWithString are class methods, which you call on the NSString class directly, no object required. On the other hand, initWithString is an instance method, which you call on the object returned by [NSString alloc].

NSString* test = [[NSString alloc] initWithString:@"test"];

NSString* test2 = [NSString stringWithString:@"test2"];

Upvotes: 1

Tommy
Tommy

Reputation: 100622

A '+' method is a class method, and can be called directly on the metaclass. It therefore has no access to instance variables.

A '-' method is an instance method, with full access to the relevant instance of the class.

E.g.

@interface SomeClass

+ (void)classMethod;
- (void)instanceMethod;

@property (nonatomic, assign) int someProperty;

@end

You can subsequently perform:

[SomeClass classMethod]; // called directly on the metaclass

Or:

SomeClass *someInstance = etc;

[someInstance instanceMethod]; // called on an instance of the class

Note that:

+ (void)classMethod
{
    NSLog(@"%d", self.someProperty); // this is impossible; someProperty belongs to
                                     // instances of the class and this is a class
                                     // method
}

Upvotes: 6

Related Questions