What is the difference of using:
+ (id) myMethod;
// Rather than
- (id) myMethod;
What is the difference of using:
+ (id) myMethod;
// Rather than
- (id) myMethod;
Using a +
declares the method as a class method, or a method that can be called directly on the class, where the class is the object. So when you have this:
@implementation Foo
+(NSString*)method1 {
return @"Foo";
}
-(NSString*)method2 {
return @"Foo";
}
@end
The methods are called in different ways:
[Foo method1]; //=> @"Foo"
Foo* f=[[Foo alloc] init];
[f method2]; //=> @"Foo"
One other thing to note is that class methods don't have access to an instance, which means they can't access any kind of instance variables.
@Linuxios pretty much summed up the concept of class and instance method. However, since you mentioned getters and setters in your title, I want to point out that in Objective-C you can use properties instead of writing your own accessor methods. For example,
In the header file, you will have something like this:
@interface MyObject : NSObject
@property (nonatomic,retain) NSSet* mySet;
@end
In the m file, you wil have something like this:
@implement MyObject
@synthesize mySet;
@end
To access the set in another class you can do it like this:
myObject.mySet; // assuming myObject is an instance of the MyObject class
The top one is a class method (no instance required) The second one is a instance variable (attached to a specific instance).
This answer explains the methods quite well:
[MyObject myMethod]; // did not have to create an instance
MyObject* myNewObject = [[MyObject alloc] init] autorelease];
[myNewObject myMethod]; // had to create an instance