Objective-c中的isa是什么意思? [英] What does isa mean in objective-c?

查看:117
本文介绍了Objective-c中的isa是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个例子来了解下面几行的含义.我无法理解这些行的实际含义.这些行来自Google的Objective-C编码指南.

I would like to know the meaning of the below written lines with an example. I'm unable to understand what the lines actually mean. The lines are from google's objective-c coding guidelines.

初始化
不要在init方法中将变量初始化为0或nil;这是多余的.

Initialization
Don't initialize variables to 0 or nil in the init method; it's redundant.

新分配的对象的所有内存都初始化为0(isa除外),因此不要通过将变量重新初始化为0或nil来使init方法混乱.

All memory for a newly allocated object is initialized to 0 (except for isa), so don't clutter up the init method by re-initializing variables to 0 or nil.

推荐答案

在幕后,Objective-C对象基本上是C结构.每个字段都包含一个名为isa的字段,该字段指向该对象是其实例的类的指针(这就是该对象和Objective-C运行时如何知道它是哪种对象的方式).

Under the hood, Objective-C objects are basically C structs. Each one contains a field called isa, which is a pointer to the class that the object is an instance of (that's how the object and Objective-C runtime knows what kind of object it is).

关于变量的初始化:在Objective-C中,实例变量会自动初始化为0(对于C类型,例如int)或nil(对于Objective-C对象).苹果公司的指导方针说,在init方法中将ivars初始化为这些值是多余的,所以不要这样做.例如,假设您有一个这样的课程:

Regarding the initialization of variables: in Objective-C, instance variables are automatically initialized to 0 (for C types like int) or nil (for Objective-C objects). Apple's guidelines say that initializing your ivars to those values in your init methods is redundant, so don't do it. For example, say you had a class like this:

@interface MyClass : NSObject
{
    int myInt;
    double myDouble;
    MyOtherClass *myObj;
}
@end

以这种方式编写init方法将是多余的,因为无论如何这些ivars都将初始化为0nil:

Writing your init method this way would be redundant, since those ivars will be initialized to 0 or nil anyway:

@implementation MyClass

- (id)init
{
    if ((self = [super init])) {
        myInt = 0;
        myDouble = 0.0;
        myObj = nil;
    }
    return self;
}

@end

您可以改为这样做:

@implementation MyClass

- (id)init
{
    return [super init];
}

@end

当然,如果希望将ivars初始化为0nil以外的值,则仍应初始化它们:

Of course, if you want the ivars to be initialized to values other than 0 or nil, you should still initialize them:

@implementation MyClass

- (id)init
{
    if ((self = [super init])) {
        myInit = 10;
        myDouble = 100.0;
        myObj = [[MyOtherClass alloc] init];
    }
    return self;
}

@end

这篇关于Objective-c中的isa是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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