-1

What is the difference of using:

+ (id) myMethod;

// Rather than
- (id) myMethod;
beakr
  • 5,709
  • 11
  • 42
  • 66
  • possible duplicate of [What do the plus and minus signs mean in Objective C next to a method?](http://stackoverflow.com/questions/2097294/what-do-the-plus-and-minus-signs-mean-in-objective-c-next-to-a-method) – vikingosegundo Jun 30 '12 at 16:16

3 Answers3

1

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
  • 34,849
  • 13
  • 91
  • 116
  • 1
    … and, therefore, class methods are not getters. They're just class methods. Also, your example would be clearer if the two methods returned different values. – Ken Thomases Jun 30 '12 at 14:39
1

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

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:

Method Syntax in Objective C

[MyObject myMethod]; // did not have to create an instance

MyObject* myNewObject = [[MyObject alloc] init] autorelease];
[myNewObject myMethod]; // had to create an instance
Community
  • 1
  • 1
tjg184
  • 4,508
  • 1
  • 27
  • 54