Call a class method from within that class

2019-01-17 07:03发布

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
}

4条回答
唯我独甜
2楼-- · 2019-01-17 07:14

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];
}
查看更多
何必那么认真
3楼-- · 2019-01-17 07:15

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.

查看更多
相关推荐>>
4楼-- · 2019-01-17 07:24

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)

查看更多
做自己的国王
5楼-- · 2019-01-17 07:33

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

So you just need to write

+classMethodB{
    [self classMethodA];
}
查看更多
登录 后发表回答