Is there a way to call a class method from another method within the same class?
For example:
+classMethodA{
}
+classMethodB{
//I would like to
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)
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];
}
In objective C 'self' is used to call other methods within the same class.
So you just need to write
+classMethodB{
[self classMethodA];
}
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.