Call instance method from class method

后端 未结 3 1787
生来不讨喜
生来不讨喜 2020-11-30 08:01

So I need to call some instance methods from class methods in Objective-C...

Example :

+(id)barWithFoo:(NSFoo *) {
[self foo]; //Raises compiler warn         


        
3条回答
  •  借酒劲吻你
    2020-11-30 08:30

    If you want to call an instance method you need an instance to call the method on.

    self is a reference to the instance that is being messaged. Thus self in a class method is the class and self in an instance method is an instance of the class.

    So, naively, you might do:

    +(id)barWithFoo:(NSFoo *) {
        [[[self alloc] init] foo]; //Raises compiler warning. 
    }
    
    -(void)foo {
    //cool stuff
    }
    

    Of course, that'd leak memory in a non-GC application (since the instance isn't being released or autoreleased). Instead of explaining why, I will point you to the Objective-C intro documentation. It is some awesome stuff, covering both Objective-C and general object oriented programming patterns.

提交回复
热议问题