本文介绍了为什么alloc方法可以添加保留计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们用Class调用alloc时,我知道Object的数量将为+1.例如:NSObject *obj = [NSObject alloc];,obj的引用计数将为1.我阅读了源代码,但是找不到能告诉我alloc为什么可以添加引用计数的代码.一些博客说alloc将调用retain方法,因此可以+1.但是我找不到一些代码可以证明这一点.有人可以告诉我为什么alloc将添加引用计数吗?

When we call alloc with a Class, I know that count of Object will +1. For example: NSObject *obj = [NSObject alloc];, The reference count of obj will be 1. I read the source code, but I can't find some code that can tell me why alloc can add the reference count. And some blog said alloc will call retain method, so it can +1. But I can't find some code can prove this. Can some one tell me why alloc will add reference count?

推荐答案

您找不到在+alloc中添加一个的通用代码.通常在+alloc内部,该对象是新创建的并获得RC1.(所以可以说添加1,因为该对象在其创建之前的RC为0.当然,这在形式上是不正确的,因为在创建时没有对象,因此它不能具有RC.零近似为null反模式.)

You cannot find generic code that adds one in +alloc. Usually inside +alloc the object is newly created and gets the RC 1. (So you can say that 1 is added, because the object before its creation has an RC of 0. Of course, this is not formally correct, because before the creation there is no object, therefore it cannot have an RC. Akin of the zero is null antipattern.)

但是,类可以覆盖+alloc以返回现有对象,而不是新对象.例如,过去已经实现单例.在这种情况下,+alloc必须发信号通知新引用(+alloc进行所有权转让),并且实际上必须添加1.类似这样的内容(示例代码):

However, classes can overwrite +alloc to return an existing object instead of a new one. For example this has been done in the past for implementing singletons. In such a case +alloc had to signal the new reference (+alloc does an ownership transfer) and really had to add 1. Something like this (sample code):

+(id)alloc
{
  if(mySingleton==nil) // it is not already created
  {
    return mySingleton = [super alloc];
  }
  return [mySingleton retain]; // ownership transfer
}

我认为在某些文章中说"+1"而不是"1"的想法是,您应该分别查看每个参考.因此,RC没有绝对值.使用引用及其对象所做的任何事情都是相对于情况的 relative .因此,有些作者总是用"+1"和"-1"来描述RC.当然,如果新创建了对象,这是没有意义的.

I think the idea of saying "+1" instead of "1" in some articles is, that you should view every reference separately. So there is no absolute value of RC. Whatever you do with a reference and its object is relative to the situation before you did it. For this reason some authors always describe the RC with "+1" and "-1". Of course, this is meaningless, if an object is newly created.

这篇关于为什么alloc方法可以添加保留计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 08:28