是自我指针吗? [英] Is self a pointer?

查看:126
本文介绍了是自我指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么样的事情是 self ?是正确的调用它的指针吗?还是它是一个变量?或者还有什么?

What kind of thing is self? Is it correct to call it a pointer? Or is it a variable? Or what else?

推荐答案

Objective-C方法实现只是一个需要两个额外参数的C函数。第一个参数是 self 变量,第二个参数是用于调用实现的选择器。第三个和任何后续的参数(如果有的话)是你的方法的实际参数。如果你有这样的方法:

An Objective-C method implementation is really just a C function that takes two extra arguments. The first argument is the self variable, and the second argument is the selector that was used to invoke the implementation. The third and any subsequent arguments (if any) are the actual arguments to your method. If you have a method like this:

@implementation MyClass

- (int) myMethod:(int) anArg
{
    NSLog (@"The selector %@ was used.", NSStringFromSelector(_cmd));
    return [self someValue] + anArg;
}

@end

然后,它大致相当于: / p>

Then, it is roughly equivalent to this:

// Implementation of MyClass's instance method "myMethod"
int MyClass_myMethod (id self, SEL _cmd, int anArg)
{
    NSLog (@"The selector %@ was used.", NSStringFromSelector(_cmd));
    return [self someValue] + anArg;
}

请记住,调用C函数和发送消息是非常不同的。向对象发送消息将导致调用实现,并且该实现由运行时确定。由于方法实现是在运行时确定的,编译器不能简单地用直接函数调用交换所有消息发送。我相信有一些方法可以告诉运行时改变给定类的给定选择器使用的方法实现。

Keep in mind though, that calling a C function and sending a message are very different. Sending a message to an object will cause invocation of an implementation, and that implementation is determined by the run-time. Since the method implementation is determined at run-time, the compiler cannot simply swap all the message-sending with straight function calls. I believe there are ways to tell the run-time to alter which method implementation to use for a given selector for a given class.

运行时确定哪个实现基于 self 的类使用。如果 self nil ,消息发送是一个无操作,因此,所有的方法实现将总是有一个由运行时调用 self 时的有效值。

The run-time determines which implementation to use based on the class of self. If self is nil, the message-sending is a no-op, therefore, all method implementations will always have a valid value for self when they are invoked by the run-time.

这篇关于是自我指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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