Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In Objective-C, I would like to know what the + and - signs next to a method definition mean.

- (void)loadPluginsAtPath:(NSString*)pluginPath errors:(NSArray **)errors;
like image 789
gyurisc Avatar asked Jan 19 '10 21:01

gyurisc


3 Answers

+ is for a class method and - is for an instance method.

E.g.

// Not actually Apple's code.
@interface NSArray : NSObject {
}
+ (NSArray *)array;
- (id)objectAtIndex:(NSUInteger)index;
@end

// somewhere else:

id myArray = [NSArray array];         // see how the message is sent to NSArray?
id obj = [myArray objectAtIndex:4];   // here the message is sent to myArray

// Btw, in production code one uses "NSArray *myArray" instead of only "id".

There's another question dealing with the difference between class and instance methods.

like image 116
Georg Schölly Avatar answered Oct 12 '22 11:10

Georg Schölly


(+) for class methods and (-) for instance method,

(+) Class methods:-

Are methods which are declared as static. The method can be called without creating an instance of the class. Class methods can only operate on class members and not on instance members as class methods are unaware of instance members. Instance methods of the class can also not be called from within a class method unless they are being called on an instance of that class.

(-) Instance methods:-

On the other hand require an instance of the class to exist before they can be called, so an instance of a class needs to be created by using the new keyword. Instance methods operate on specific instances of classes. Instance methods are not declared as static.

How to create?

@interface CustomClass : NSObject

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

@end

How to use?

[CustomClass classMethod];

CustomClass *classObject = [[CustomClass alloc] init];
[classObject instanceMethod];
like image 24
Vandit Mehta Avatar answered Oct 12 '22 11:10

Vandit Mehta


+ methods are class methods - that is, methods which do not have access to an instances properties. Used for methods like alloc or helper methods for the class that do not require access to instance variables

- methods are instance methods - relate to a single instance of an object. Usually used for most methods on a class.

See the Language Specification for more detail.

like image 27
Robert Christie Avatar answered Oct 12 '22 11:10

Robert Christie