自我是指针吗?

ope*_*rog 4 iphone cocoa cocoa-touch objective-c

什么样的东西self?称它为指针是否正确?或者它是变量?还有什么?

dre*_*lax 15

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

@implementation MyClass

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

@end
Run Code Online (Sandbox Code Playgroud)

然后,它大致相当于:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

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

运行时根据类来确定要使用的实现self.如果selfnil,则消息发送是无操作,因此,所有方法实现将始终具有self运行时调用它们的有效值.


Adr*_*ian 5

self实际上是定义于NSObject:

- (id)self;
Run Code Online (Sandbox Code Playgroud)

这样self的类型的id,而这又是在Objective-C运行定义:

typedef struct objc_object {
    Class isa;
} *id;
Run Code Online (Sandbox Code Playgroud)

所以,是的,self它只是指向Objective-C对象的指针.

有关更多信息,请参阅init方法的文档.