gpt4 book ai didi

objective-c - Cocoa 中的引用计数

转载 作者:行者123 更新时间:2023-12-03 17:44:46 24 4
gpt4 key购买 nike

我认为根据我正在阅读的“Cocoa 设计模式”一书,保留函数是使用如下内容实现的:

   - (int)retainCount
// Returns the receiver's current reference count
{
int result = 1; // receiver not in table, its count is 1
void *tableValue = NSMapGet(
[[self class] _myRefCountMapTable], self);
if(NULL != tableValue )
{ // if receiver is in table, its count is the value stored
result = (int)tableValue;
}
return result;
}

- (id)retain
// Increases the receiver's reference count
{
// store the increased value in the table
NSMapInsert([[self class] _myRefCountMapTable], self,
(void *)([self retainCount] + 1));
return self;
}

正如示例所示,每个引用对象都有相同的 self 成员。这是怎么发生的?也许我不明白 self 的含义 - 我认为它就像 C++ 中的“this”。

如果我只使用赋值运算符(A=B),它会复制指针(self)吗?我虽然它会使用“copywithzone”,但它的亲戚和“ self ”成员不会相等。此外,我认为 copywithzone 就像 c++ 中的复制构造函数。

我想我在这两个世界之间感到困惑。

最佳答案

As the example imply every reference object …

不存在“引用对象”这样的东西。我怀疑这不是你的意思,所以请澄清。

has the same self member.

对象没有成员(实例有实例变量,概念相似但实现不一样)。

self 不是“成员”,也不是实例变量。请注意,类也有 selfself 是消息的特殊隐藏参数,包含作为消息接收者的对象。

不,self 不会同时引用每个对象。如果将相同的消息发送到两个不同的对象,即使是同一类,self 参数将在每个消息中包含不同的指针。

maybe I don't understand the meaning of self - I though it's like "this" in C++.

据我了解“this”,是的。 self 是接收消息的对象 - 在您的示例中,该对象正在保留或询问其保留计数。

If I just use assignment operator (A=B) Does it copy the pointer(self) and that's it ?

如果Bself,则复制的指针只会是self。也就是说,如果您说A = self,那么它将把self指针复制到A。如果你说 B = self 然后你说 A = B,同样的事情,因为 Bself 包含同一个指针。如果您没有说过B = self,那么B可能是其他值,因此其他值将被复制到A。假设 AB 是指针变量。

它将复制您告诉它复制的值(指针)。没有别的了。

I though it would use "copywithzone" and it's relatives and the "self" members won't be equal.

没有。当有东西向对象发送 copyWithZone: 消息时,仅向该对象发送 copyWithZone: 消息(不要省略冒号 - 它们很重要)。最常见的方法是向其发送 copy 消息,因为这将依次发送 copyWithZone: 消息。

此外,即使是“复制”也并不总是复制对象。不可变对象(immutable对象)可以实现 copyWithZone: 来返回 [self keep]

但是,普通赋值永远不会复制对象。它仅复制指针。

Moreover, I though copywithzone is like copy constructor in c++.

大概。我对 C++ 的了解不够多,无法判断它有多相似。

关于objective-c - Cocoa 中的引用计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3184970/

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