What is the difference between class and instance methods? - objective-c

What's the difference between a class method and an instance method?
Are instance methods the accessors (getters and setters) while class methods are pretty much everything else?

Like most of the other answers have said, instance methods use an instance of a class, whereas a class method can be used with just the class name. In Objective-C they are defined thusly:
#interface MyClass : NSObject
+ (void)aClassMethod;
- (void)anInstanceMethod;
#end
They could then be used like so:
[MyClass aClassMethod];
MyClass *object = [[MyClass alloc] init];
[object anInstanceMethod];
Some real world examples of class methods are the convenience methods on many Foundation classes like NSString's +stringWithFormat: or NSArray's +arrayWithArray:. An instance method would be NSArray's -count method.

All the technical details have been nicely covered in the other answers. I just want to share a simple analogy that I think nicely illustrates the difference between a class and an instance:
A class is like the blueprint of a house: You only have one blueprint and (usually) you can't do that much with the blueprint alone.
An instance (or an object) is the actual house that you build based on the blueprint: You can build lots of houses from the same blueprint. You can then paint the walls a different color in each of the houses, just as you can independently change the properties of each instance of a class without affecting the other instances.

Like the other answers have said, instance methods operate on an object and has access to its instance variables, while a class method operates on a class as a whole and has no access to a particular instance's variables (unless you pass the instance in as a parameter).
A good example of an class method is a counter-type method, which returns the total number of instances of a class. Class methods start with a +, while instance ones start with an -.
For example:
static int numberOfPeople = 0;
#interface MNPerson : NSObject {
int age; //instance variable
}
+ (int)population; //class method. Returns how many people have been made.
- (id)init; //instance. Constructs object, increments numberOfPeople by one.
- (int)age; //instance. returns the person age
#end
#implementation MNPerson
- (id)init{
if (self = [super init]){
numberOfPeople++;
age = 0;
}
return self;
}
+ (int)population{
return numberOfPeople;
}
- (int)age{
return age;
}
#end
main.m:
MNPerson *micmoo = [[MNPerson alloc] init];
MNPerson *jon = [[MNPerson alloc] init];
NSLog(#"Age: %d",[micmoo age]);
NSLog(#"%Number Of people: %d",[MNPerson population]);
Output:
Age: 0
Number Of people: 2
Another example is if you have a method that you want the user to be able to call, sometimes its good to make that a class method. For example, if you have a class called MathFunctions, you can do this:
+ (int)square:(int)num{
return num * num;
}
So then the user would call:
[MathFunctions square:34];
without ever having to instantiate the class!
You can also use class functions for returning autoreleased objects, like NSArray's
+ (NSArray *)arrayWithObject:(id)object
That takes an object, puts it in an array, and returns an autoreleased version of the array that doesn't have to be memory managed, great for temperorary arrays and what not.
I hope you now understand when and/or why you should use class methods!!

An instance method applies to an instance of the class (i.e. an object) whereas a class method applies to the class itself.
In C# a class method is marked static. Methods and properties not marked static are instance methods.
class Foo {
public static void ClassMethod() { ... }
public void InstanceMethod() { ... }
}

The answer to your question is not specific to objective-c, however in different languages, Class methods may be called static methods.
The difference between class methods and instance methods are
Class methods
Operate on Class variables (they can not access instance variables)
Do not require an object to be instantiated to be applied
Sometimes can be a code smell (some people who are new to OOP use as a crutch to do Structured Programming in an OO enviroment)
Instance methods
Operate on instances variables and class variables
Must have an instanciated object to operate on

I think the best way to understand this is to look at alloc and init. It was this explanation that allowed me to understand the differences.
Class Method
A class method is applied to the class as a whole. If you check the alloc method, that's a class method denoted by the + before the method declaration. It's a class method because it is applied to the class to make a specific instance of that class.
Instance Method
You use an instance method to modify a specific instance of a class that is unique to that instance, rather than to the class as a whole. init for example (denoted with a - before the method declaration), is an instance method because you are normally modifying the properties of that class after it has been created with alloc.
Example
NSString *myString = [NSString alloc];
You are calling the class method alloc in order to generate an instance of that class. Notice how the receiver of the message is a class.
[myString initWithFormat:#"Hope this answer helps someone"];
You are modifying the instance of NSString called myString by setting some properties on that instance. Notice how the receiver of the message is an instance (object of class NSString).

Class methods are usually used to create instances of that class
For example, [NSString stringWithFormat:#"SomeParameter"]; returns an NSString instance with the parameter that is sent to it. Hence, because it is a Class method that returns an object of its type, it is also called a convenience method.

So if I understand it correctly.
A class method does not need you to allocate instance of that object to use / process it. A class method is self contained and can operate without any dependence of the state of any object of that class. A class method is expected to allocate memory for all its own work and deallocate when done, since no instance of that class will be able to free any memory allocated in previous calls to the class method.
A instance method is just the opposite. You cannot call it unless you allocate a instance of that class. Its like a normal class that has a constructor and can have a destructor (that cleans up all the allocated memory).
In most probability (unless you are writing a reusable library, you should not need a class variable.

Instances methods operate on instances of classes (ie, "objects"). Class methods are associated with classes (most languages use the keyword static for these guys).

Take for example a game where lots of cars are spawned.. each belongs to the class CCar.
When a car is instantiated, it makes a call to
[CCar registerCar:self]
So the CCar class, can make a list of every CCar instantiated.
Let's say the user finishes a level, and wants to remove all cars... you could either:
1- Go through a list of every CCar you created manually, and do whicheverCar.remove();
or
2- Add a removeAllCars method to CCar, which will do that for you when you call [CCar removeAllCars]. I.e. allCars[n].remove();
Or for example, you allow the user to specify a default font size for the whole app, which is loaded and saved at startup.
Without the class method, you might have to do something like
fontSize = thisMenu.getParent().fontHandler.getDefaultFontSize();
With the class method, you could get away with [FontHandler getDefaultFontSize].
As for your removeVowels function, you'll find that languages like C# actually have both with certain methods such as toLower or toUpper.
e.g. myString.removeVowels() and String.removeVowels(myString) (in ObjC that would be [String removeVowels:myString]).
In this case the instance likely calls the class method, so both are available.
i.e.
public function toLower():String{
return String.toLower();
}
public static function toLower( String inString):String{
//do stuff to string..
return newString;
}
basically, myString.toLower() calls [String toLower:ownValue]
There's no definitive answer, but if you feel like shoving a class method in would improve your code, give it a shot, and bear in mind that a class method will only let you use other class methods/variables.

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.

In Objective-C all methods start with either a "-" or "+" character.
Example:
#interface MyClass : NSObject
// instance method
- (void) instanceMethod;
+ (void) classMethod;
#end
The "+" and "-" characters specify whether a method is a class method or an instance method respectively.
The difference would be clear if we call these methods. Here the methods are declared in MyClass.
instance method require an instance of the class:
MyClass* myClass = [[MyClass alloc] init];
[myClass instanceMethod];
Inside MyClass other methods can call instance methods of MyClass using self:
-(void) someMethod
{
[self instanceMethod];
}
But, class methods must be called on the class itself:
[MyClass classMethod];
Or:
MyClass* myClass = [[MyClass alloc] init];
[myClass class] classMethod];
This won't work:
// Error
[myClass classMethod];
// Error
[self classMethod];

CLASS METHODS
A class method typically either creates a new instance of the class or retrieves some global properties of the class. Class methods do not operate on an instance or have any access to instance variable.
INSTANCE METHODS
An instance method operates on a particular instance of the class. For example, the accessors method that you implemented are all instance methods. You use them to set or get the instance variables of a particular object.
INVOKE
To invoke an instance method, you send the message to an instance of the class.
To invoke a class method, you send the message to the class directly.
Source: IOS - Objective-C - Class Methods And Instance Methods

Class methods can't change or know the value of any instance variable. That should be the criteria for knowing if an instance method can be a class method.

Also remember, the same idea applies to variables. You will come across terms like static, member, instance, class and so on when talking about variables the same as you would for methods/functions.
It seems the common term in the Obj-C community is ivar for instance variable, but I am not an Obj-C guy, yet.

An update to the above answers, I agree instance methods use an instance of a class, whereas a class method can be used with just the class name.
There is NO more any difference between instance method & class method after automatic reference counting came to existence in Objective-C.
For Example[NS StringWithformat:..] a class method & [[NSString alloc] initwihtformat:..] an instance method, both are same after ARC

Note: This is only in pseudo code format
Class method
Almost does all it needs to do is during compile time. It doesn't need any user input, nor the computation of it is based on an instance. Everything about it is based on the class/blueprint——which is unique ie you don't have multiple blueprints for one class. Can you have different variations during compile time? No, therefore the class is unique and so no matter how many times you call a class method the pointer pointing to it would be the same.
PlanetOfLiving: return #"Earth" // No matter how many times you run this method...nothing changes.
Instance Method
On the contrary instance method happens during runtime, since it is only then that you have created an instance of something which could vary upon every instantiation.
initWithName: #"John" lastName: #"Doe"Age:12 #"cool"
initWithName: #"Donald" lastName: #"Drumpf"Age:5 attitude:#"He started"
initWithName: #"President" lastName: #"Obama"Age:54 attitude: #"Awesome"
//As you can see the value can change for each instance.
If you are coming from other languages Static methods are same as class methods.
If you are coming from Swift, type methods are same as class methods.

Adding to above answers
Class method will work on class, we will use this for general purpose where like +stringWithFormat, size of class and most importantly for init etc
NSString *str = [NSString stringWithFormat:#"%.02f%%",someFloat];
Instance Method will work on an instance of a class not on a class like we are having two persons and we want to get know the balance of each separately here we need to use instance method. Because it won't return general response. e.g. like determine the count of NSSArray etc.
[johnson getAccountBalance];
[ankit getAccountBalance];

Related

What does the + character before a method mean in Objective C? [duplicate]

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;
+ 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.
(+) 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];
+ 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.
The definitive explanation of this from Apple is here, under the 'Methods and Messaging' section:
https://developer.apple.com/library/mac/referencelibrary/GettingStarted/RoadMapOSX/books/WriteObjective-CCode/WriteObjective-CCode/WriteObjective-CCode.html
In brief:
+ means 'class method'
(method can be called without an instance of the class being instantiated). So you call it like this:
[className classMethod];
- means 'instance method'
You need to instantiate an object first, then you can call the method on the object). You can manually instantiate an object like this:
SomeClass* myInstance = [[SomeClass alloc] init];
(this essentially allocates memory space for the object then initalises the object in that space - an oversimplification but a good way to think about it. You can alloc and init the object seperately but never do this - it can lead to nasty issues related to pointers and memory management)
Then call the instance method:
[myInstance instanceMethod]
An alternative way to get an instance of an object in Objective C is like this:
NSNumber *myNumber = [NSNumber numberWithInt:123];
which is calling the 'numberWithInt' class method of the NSNumber class, which is a 'factory' method (i.e. a method that provides you with a 'ready made instance' of an object).
Objective C also allows the creation of certain object instances directly using special syntax, like in the case of a string like this:
NSString *myStringInstance = #"abc";

Can we use class methods (which start with + sign) with instances of that class

Just wondering if there is any way we can use class methods (i.e. +(void)mymethod ) with instance of that class?
Also is it possible to access instance variables in my class methods?
No You cant invoke a static method with the instance. Static method can only invoked by using class name.
You cant access instance variables from static methods. Only static variables can be access.
is any way we can use class methods (i.e. +(void)mymethod ) with instance of that class?
Well of course you can. The class nothing but an object that you can retrieve from the instance, so just go ahead and do it.
[[myInstance class] myClassMethod]
is it possible to access instance variables in my class methods?
No, and for obvious reasons: it doesn't make any sense.
You're in a class method, to which instance would like you refer to? The last one created? The first one? As far as you know there might even not be an instance allocated. Let's try with an example
Here's a class declaration (just the interface will suffice)
#interface FancyClass : NSObject
#property NSString *name;
+ (void)myFancyClassMethod;
#end
Now let's declare a couple of instances
FancyClass *fancy1 = [FancyClass new];
fancy1.name = #"Hi I'm Fancy 1";
FancyClass *fancy2 = [FancyClass new];
fancy2.name = #"Hi I'm Fancy 2";
Now if you hypothetically could access the instance variables from myFancyClassMethod's implementation, what value would you expect to read for name? Do you see the nonsense?
An instance var belongs to an instance. Now if you can access instance var within a class method, which instance that instance var belongs to, among all the instances floating out there?

Why can -respondsToSelector: instance method be used on class name or class object?

In Programming in Objective C, 4e, Chapter 9, Program 9.3:
#import "Square.h"
int main (int argc, char * argv[])
{
#autoreleasepool {
Square *mySquare = [[Square alloc] init];
...
// respondsTo:
if ( [mySquare respondsToSelector: #selector (setSide:)] == YES )
NSLog (#"mySquare responds to setSide: method");
...
if ( [Square respondsToSelector: #selector (alloc)] == YES )
NSLog (#"Square class responds to alloc method");
...
}
return 0;
}
Q1:
Since -respondsToSelector: is an instance method, not a class method, why would it be possible to use it on Square class directly?
Q2:
The book says you can use Square here instead of [Square class]. Is it only a exceptional shortcut, or is there any mechanism behind this?
Any help would be really appreciated! Thanks in advance!
From The Objective-C Programming Language, Objects, class, and Messaging,
All objects, classes and instances alike, need an interface to the
runtime system. Both class objects and instances should be able to
introspect about their abilities and to report their place in the
inheritance hierarchy. It’s the province of the NSObject class to
provide this interface.
So that NSObject methods don’t have to be implemented twice—once to
provide a runtime interface for instances and again to duplicate that
interface for class objects—class objects are given special dispensation to perform instance methods defined in the root class.
When a class object receives a message that it can’t respond to with a
class method, the runtime system determines whether there’s a root
instance method that can respond. The only instance methods that a
class object can perform are those defined in the root class, and only if there’s no class method that can do the job.
In this case, NSObject is the root class. As NSObject instances all comply with NSObject protocol, where -respondsToSelector: is defined, most class objects should be able to perform -respondsToSelector:.
Q1:
The simple answer is that, in addition to class methods, you can call any instances method of the root class (whatever the root class of your class is; in this case, NSObject) on a class object.
The more complicated answer is that class objects are instances of metaclasses. Whereas instance methods are methods on an instance, which are defined in the class; class methods are methods on the class object, which are defined in the metaclass. Each class has its own metaclass. The inheritance of metaclasses follows that of their classes; i.e. NSString's metaclass inherits from NSObject's metaclass. Ultimately, the root class's metaclass inherits from the root class; i.e. NSObject's metaclass inherits from NSObject. That is why all of NSObject's instance methods are available to class objects.
Q2:
[Square class] calls the class method +class (this is unrelated to -class). +class is essentially an identity method that simply returns the thing called on it (just like -self); i.e. if foo is a pointer to a class object, then [foo class] is the same as foo.
So +class seems pretty useless; why do we use it? That is because in the grammar of the Objective-C language, a class name is not a valid expression (unlike Smalltalk). So you cannot say id bar = Square;; that would not compile. As a special case in the grammar, a class name is allowed in place of the receiver in a message call expression, and the message is sent to the class object; i.e. [Square something]. So if you want to use the class object in any other expression context, we do this in a roundabout way by calling an identity method like +class; i.e. [Square class] is an expression that can be used in any expression context ([Square self] would also work, but we use [Square class] by convention, which is unfortunate, since it is confused with -class); we would have liked to just use Square, but can't due to the language.
In your case, it is already the receiver in a message call expression, so it is unnecessary to do [Square class]; Square already works there.
//Q1:
Since -respondsToSelector: is an instance method, not a class method, why would it be possible to use it on Square class directly?//
You seem to have this notion that class methods cannot be called from instance methods (and vice versa). On the contrary, it would seem to be the intent of the method -respondsToSelector to do so, most likely by getting the class of the sender with the -class method, then querying if the class responds to the selector and returning YES or NO. In a more localized example, consider the following:
-(void)someInstanceMethod{
[MyCurrentClass doClassMethod]; //basic equivalent of [self doClassMethid];
}
Is perfectly valid in Objective-C, provided MyCurrentClass is all alloc'd and init'ed.
//Q2:
The book says you can use Square here instead of [Square class]. Is it only a exceptional shortcut, or is there any mechanism behind this?//
It is completely redundant to send -class to a Class! It makes little sense, and is just extra unnecessary code. -class just queries for the reciever's class, no matter if it is an instance or Class object.
The Objective C run-time currently implements a class as an instance object of some other class. Thus a class will response to certain instance methods.
The real implementation, straight out of NSObject.m is as such:
- (BOOL)respondsToSelector:(SEL)aSelector {
PF_HELLO("")
return class_respondsToSelector( isa, aSelector );
}
Now, I have no idea why that PF_HELLO("") is there, but as you can see, it's literally ASKING the CLASS in the RUNTIME "Hey, do you have a method for this isa [instance] called aSelector?"
And, in Objective-C, class methods ALSO belong to instances, but, however, take lower precedence (the instance method of the same name as the class method is called before the class method).
Another aspect of Objective-C's Dynamic Typing is that the id type is in fact declared as follows:
typedef struct objc_class *Class;
typedef struct objc_object {
Class isa;
} *id;
So your instance object is in fact, a Class pointer. This means your -respondsToSelector messages go to the Class of the instance type as well. In your case, it means that -respondsToSelector is going to the objc_class FIRST.
Now in a test case, (straight out of libFoundation), my answer would be summed up like this:
Test *tst = [Test new];
fail_unless([tst respondsToSelector:#selector(testInstanceMethod)], "-[Test respondsToSelector:] returned NO for a valid instance method (testInstanceMethod).");
fail_if([tst respondsToSelector:#selector(testClassMethod)], "-[Test respondsToSelector:] returned YES for a class method (testInstanceMethod).");
fail_unless([Test respondsToSelector:#selector(testClassMethod)], "+[Test respondsToSelector:] returned NO for a valid class method (testClassMethod).");
fail_if([Test respondsToSelector:#selector(testInstanceMethod)], "+[Test respondsToSelector:] returned YES for an instance method (testInstanceMethod).");
fail_unless([tst respondsToSelector:#selector(init)], "-[Test respondsToSelector:] returned NO for an inherited instance method (-[NSObject init].");
fail_unless([Test respondsToSelector:#selector(alloc)], "+[Test respondsToSelector:] returned NO for an inherited class method (+[NSObject alloc]).");
[tst release];

Class Objects and Instance Variables in Objective-C

I'm having a hard time wrapping my head around this concept. I'll take the quote exactly from the book:
Class objects also inherit from the classes above them in the hierarchy. But because they don’t have instance variables (only instances do), they inherit only methods.
Correct me if I'm wrong, but a class object would be this:
NSString *aString = [[NSString alloc]initWithString:#"abc.."];
The class object in this case is *aString -- am I correct so far?
The thing that confuses me is the second sentence in the quote above, "But because they don’t have instance variables (only instances do), they inherit only methods."
I thought that an object (in this case *aString) was the instance of the NSString class.
The second sentence above is implying that an instance is something different. It's not making any sense to me.
You are incorrect.
NSString *aString = [[NSString alloc] initWithString:#"abc..."];
In this line, we have, from left-to-right:
A type: NSString *
A variable name: aString
an assignment
A Class: NSString
An invocation of a class method: +alloc
An invocation of an instance method on the return value of the class method: -initWithString:
An object being passed as a parameter to the instance method: #"abc..."
In Objective-C, a Class is actually a kind of object. You can interact with them in many of the same ways that you can instances, but since they are "classes", they cannot have instance variables (since instance variables, by definition, are only for instances). Classes only have methods. They inherit from other Classes, and this is how object inheritance is implemented.
For more information on this, check out this awesome blog post by Greg Parker: http://www.sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html
In ObjectiveC the classes themselves are objects.
In your example, aString is an NSString object BUT NSString is also an object, it's a class object.
Class object have methods declared like this for example
#interface MyClass : NSObject
{
}
+(void) myClassMethod;
#end
To call the myClassMethod method you type :
[MyClass myClassMethod];
But there is no static variable like in C++ or Java so the class object (here MyClass) can't contain variable but an instance of the class MyClass can have variable.
So to resume NSString is a class object and aString is an instance object of NSString.
In Objective-C, there are instances, which are the objects that you create and use, and there are (semi-hidden) objects which are class objects, and which are created by the compiler. The class object is where the methods for the class are stored; each instance holds only its own data (i.e., instance variables).
Bob * myBob = [[Bob alloc] init];
Here, myBob is an instance. Every instance has a reference back to its class object.1 When you call a method on an instance:
[myBob frogBlastTheVentCore];
the runtime goes and looks up the method in the class object, then uses the instance and the instance's data to perform the method. That's the basic organization of objects in Obj-C: instance objects hold data and have references to their class objects, which hold methods. There is only one class object per class; all instances of that class have a reference to the same class object.
A class (considered as a "type" rather than an object for a moment2) is said to inherit from another class:
#interface Bob : NSObject {
NSColor * uniformColor;
}
+ (BOOL) willShootAtPlayer;
- (void) frogBlastTheVentCore;
#end
#interface VacuBob : Bob {}
#end
Here, VacuBob is a subclass of Bob; any instance of VacuBob has its own uniformColor instance variable. Likewise, there is a class object VacuBob created by the compiler; it too inherits from Bob -- from the Bob class object. This means that the VacuBob class object also has the method willShootAtPlayer.
In the line you posted:
... aString = [NSString alloc] ...
the class object is actually NSString here. You are calling the class method named +[NSString alloc]3 (class methods being denoted by + rather than -4). When a class name is used as the receiver of a message (the first half of the bracketed expression), it refers to the class object5. In this case, then, both NSString and aString are objects; they are just two different kinds of objects; aString is an instance.
Dave DeLong linked to a good post on this (the diagram in particular pretty much lays everything out); for more info, you should also check out Matt Neuberg's description of "The Secret Life of Classes" in his iOS book. It describes the creation of class objects, their uses, and the other things that they do besides holding methods.
1This is the isa pointer: myBob->isa refers to the Bob class object.
2A variable referring to a class object has type Class. An instance object's type is its class. So the type of Bob is Class and the type of myBob is Bob * (that is, a pointer to an object, whose type is Bob). The distinction between the type of a variable and the type of an object may be cause some confusion here.
3The return value of alloc happens to be an instance of NSString, on which you call the instance method initWithString:
4Class methods parallel instance methods in that they are called with the class object itself as an argument. Since class objects have no data of their own, the use of class methods is perhaps more limited than other OO languages; class methods are most often used for vending instances.
5When it is used in the declaration of a variable: NSString * mySting;, it is the name of the type of the variable.

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;
+ 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.
(+) 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];
+ 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.
The definitive explanation of this from Apple is here, under the 'Methods and Messaging' section:
https://developer.apple.com/library/mac/referencelibrary/GettingStarted/RoadMapOSX/books/WriteObjective-CCode/WriteObjective-CCode/WriteObjective-CCode.html
In brief:
+ means 'class method'
(method can be called without an instance of the class being instantiated). So you call it like this:
[className classMethod];
- means 'instance method'
You need to instantiate an object first, then you can call the method on the object). You can manually instantiate an object like this:
SomeClass* myInstance = [[SomeClass alloc] init];
(this essentially allocates memory space for the object then initalises the object in that space - an oversimplification but a good way to think about it. You can alloc and init the object seperately but never do this - it can lead to nasty issues related to pointers and memory management)
Then call the instance method:
[myInstance instanceMethod]
An alternative way to get an instance of an object in Objective C is like this:
NSNumber *myNumber = [NSNumber numberWithInt:123];
which is calling the 'numberWithInt' class method of the NSNumber class, which is a 'factory' method (i.e. a method that provides you with a 'ready made instance' of an object).
Objective C also allows the creation of certain object instances directly using special syntax, like in the case of a string like this:
NSString *myStringInstance = #"abc";