Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call instance method from class method

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

Example :

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

-(void)foo {
//cool stuff
}

So my question; StackOverFlow is how do you do such things in Objective-C, I'm new kinda to OOP, so am I mad, or is there a way to do this?

like image 491
Moot Avatar asked Jan 23 '10 02:01

Moot


People also ask

Can we call instance method from class method?

Calling Instance Method:We have to create the class object; then, we can call the instance method in the main method.

Can class methods access instance methods?

Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.

Can we call instance method from class method in Python?

You can call instance method with classmethod when treating it like instance method and add class as instance.

Can a class method call an instance method Ruby?

In Ruby, a method provides functionality to an Object. A class method provides functionality to a class itself, while an instance method provides functionality to one instance of a class. We cannot call an instance method on the class itself, and we cannot directly call a class method on an instance.


1 Answers

There is not a way to do this. It simply doesn't work with object-orientation.

Classes are kinds of things. That's it. They simply describe what that kind of thing does.

An example might be that you have a 'Dog' class. You would have instance methods that would define how a dog wags its tail or how it eats. You might have a class method to purchase a dog.

My pet dog Fido is an instance of class dog. I can send Fido messages, telling him to wag his tail and eat his food. I cannot, however, ask the class 'Dog' to wag its tail; whose tail would wag? Would it be Fido's, or would it be my neighbor's dog?

When you send a message to the class, you don't have a 'self' variable to work with. There's nothing that could tell itself to wag its own tail. Class messages are mostly used for creating instances of the class or getting at other general information.

Edit: To clarify, that last paragraph is an oversimplification. There is a 'self' variable in class methods as bbum describes - it's the computer's reference to the description of the class. That said, I don't think I've ever had an occasion to use 'self' in a class method.

like image 137
mbauman Avatar answered Oct 21 '22 05:10

mbauman