简体   繁体   中英

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.

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.

Eg

@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
}

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.)

- (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"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM