复制对象时的内存管理

And*_*kha 1 memory-management copy objective-c retaincount

我知道我的问题已经在StackOverflow上讨论过,但我发现答案不能完全满足我的需求.所以问题是:

NSMutableArray *firstArray = [[NSMutableArray alloc] initWithObjects: obj1,obj2,nil];
NSMutableArray *secondArray = [[NSMutableArray alloc] init];
secondArray = [firstArray mutableCopy];
Run Code Online (Sandbox Code Playgroud)

现在,secondArray的保留计数是多少?2还是1?我应该发布两次还是只发一次?copy或mutableCopy是否会增加COPYING(此事件中为secondArray)对象的保留计数?

Dar*_*ust 5

你永远不应该关心绝对保留计数.只有你是"平衡",这意味着每一个alloc,new*,copy,mutableCopyretain你需要一个相应的releaseautorelease(不使用ARC时,即是).

如果您将此规则应用于每一行,您可以看到第二行有一个alloc,但没有释放.事实上,在这里分配一个实例绝对没用,因为你无论如何都对它不感兴趣.所以它应该简单地读:

NSMutableArray *firstArray = [[NSMutableArray alloc] initWithObjects: obj1,obj2,nil];
NSMutableArray *secondArray = [firstArray mutableCopy];
// There is no third line.
Run Code Online (Sandbox Code Playgroud)

但是让我们讨论你的原始代码,看看发生了什么:

NSMutableArray *firstArray = [[NSMutableArray alloc] initWithObjects: obj1,obj2,nil];
NSMutableArray *secondArray = [[NSMutableArray alloc] init];
// secondArray points to a new instance of type NSMutableArray
secondArray = [firstArray mutableCopy];
// You have copied another array (created a new NSMutableArray
// instance) and have overwritten the pointer to the old array.
// This means that the instance allocated in line 2 is still there
// (was not released) but you don't have a pointer to it any more.
// The array from line 2 has been leaked.
Run Code Online (Sandbox Code Playgroud)

在Objective-C中,我们经常谈到所有权:很少有方法可以让你成为对象的"拥有者".这些是:

  • alloc
  • new*,如在 newFoo
  • copymutableCopy
  • retain

如果你打电话给这些,你会得到一个你负责的对象.这意味着您需要调用相应数量的release和/或autorelease这些对象.例如,你的罚款,如果你这样做[[obj retain] retain];,然后[[obj autorelease] release];