gpt4 book ai didi

objective-c - 在objective-c中isa是什么意思?

转载 作者:IT老高 更新时间:2023-10-28 11:44:26 25 4
gpt4 key购买 nike

我想通过一个例子来了解以下文字的含义。我无法理解这些线条的实际含义。这些行来自 google 的 Objective-c 编码指南。

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

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 运行时知道它是什么类型的对象的方式)。

关于变量的初始化:在Objective-C中,实例变量自动初始化为0(对于像int这样的C类型)或者nil(对于 Objective-C 对象)。 Apple 的指导方针说,将您的 ivars 初始化为 init 方法中的那些值是多余的,所以不要这样做。例如,假设您有这样的类(class):

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

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

@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 以外的值,您仍然应该初始化它们:

@implementation MyClass

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

@end

关于objective-c - 在objective-c中isa是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3405224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com