Call a class method from within that class

后端 未结 4 1428
孤城傲影
孤城傲影 2020-12-08 14:39

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

For example:

+classMethodA{
}

+classMethodB{
    //I would like to          


        
相关标签:
4条回答
  • 2020-12-08 15:23

    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)

    0 讨论(0)
  • 2020-12-08 15:23

    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];
    }
    
    0 讨论(0)
  • 2020-12-08 15:31

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

    So you just need to write

    +classMethodB{
        [self classMethodA];
    }
    
    0 讨论(0)
  • 2020-12-08 15:33

    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.

    0 讨论(0)
提交回复
热议问题