prostock
prostock

Reputation: 9545

Call a class method from within that class

Is there a way to call a class method from another method within the same class?

For example:

+classMethodA{
}

+classMethodB{
    //I would like to call classMethodA here
}

Upvotes: 27

Views: 26911

Answers (4)

Indra Adam
Indra Adam

Reputation: 269

In objective C 'self' is used to call other methods within the same class.

So you just need to write

+classMethodB{
    [self classMethodA];
}

Upvotes: 4

Jon Reid
Jon Reid

Reputation: 20980

In a class method, self refers to the class being messaged. So from within another class method (say classMethodB), use:

+ (void)classMethodB
{
    // ...
    [self classMethodA];
    // ...
}

From within an instance method (say instanceMethodB), use:

- (void)instanceMethodB
{
    // ...
    [[self class] classMethodA];
    // ...
}

Note that neither presumes which class you are messaging. The actual class may be a subclass.

Upvotes: 65

NSGod
NSGod

Reputation: 22948

Sure.

Say you have these methods defined:

@interface MDPerson : NSObject {
    NSString *firstName;
    NSString *lastName;

}

+ (id)person;
+ (id)personWithFirstName:(NSString *)aFirst lastName:(NSString *)aLast;
- (id)initWithFirstName:(NSString *)aFirst lastName:(NSString *)aLast;


@property (copy) NSString *firstName;
@property (copy) NSString *lastName;

@end

The first 2 class methods could be implemented as follows:

+ (id)person {
   return [[self class] personWithFirstName:@"John" lastName:@"Doe"];
}

+ (id)personWithFirstName:(NSString *)aFirst lastName:(NSString *)aLast {
    return [[[[self class] alloc] initWithFirstName:aFirst lastName:aLast]
                                                      autorelease];
}

Upvotes: 3

Tom Jefferys
Tom Jefferys

Reputation: 13310

Should be as simple as:

[MyClass classMethodA];

If that's not working, make sure you have the method signature defined in the class's interface. (Usually in a .h file)

Upvotes: 8

Related Questions