从类方法调用实例方法 [英] Call instance method from class method

查看:105
本文介绍了从类方法调用实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我需要从objecitve-c ...中的类方法调用一些实例方法。

So I need to call some instance methods from class methods in objecitve-c...

示例:

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

-(void)foo {
//cool stuff
}

所以我的问题; StackOverFlow是如何在Objective-C中做这样的事情,我对OOP有新意,所以我疯了,还是有办法做这个?

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?

推荐答案

没有办法做到这一点。它根本不适用于面向对象。

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.

一个例子可能是你有一个'Dog'类。你将有实例方法来定义狗如何拖尾或它的吃法。您可能有一个类方法来购买狗。

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.

我的宠物狗Fido是类狗的一个实例。我可以发送Fido消息,告诉他摇摇尾巴,吃他的食物。然而,我不能要求班级狗摇晃它的尾巴;他的尾巴会摇摆?是Fido的,还是它的邻居的狗?

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?

当你向类发送消息时,没有'self'变量来处理。没有什么可以告诉自己摇摆自己的尾巴。类消息主要用于创建类的实例或获取其他一般信息。

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.

编辑:要澄清,最后一段是简单化。在bbum描述的类方法中有一个'self'变量 - 它是计算机对类的描述的引用。也就是说,我不认为我曾经有过一个机会在类方法中使用self。

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.

这篇关于从类方法调用实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆