1

如果我调用[alloc] init]一个已经初始化和分配的对象会发生什么?

在我的特殊情况下,我有一个我在超类中使用的NSMutableArray初始化ParentNSMutableArray* someArray = [NSMutableArray alloc] init];

在子类Child中,我需要someArray在特定索引处插入一个对象,例如 3。
因此,如果数组没有项目,或者它的项目少于我尝试插入的索引(数组有 4 个项目,并且我想在索引 10 处插入)它会崩溃。

如果我在课堂someArray上再次初始化会发生什么?Child存储的指针someArray会被我正在初始化的新指针替换,而“旧”指针会泄漏吗?

编辑:

抱歉,我的术语有点不对劲。我不是说做[someObject alloc],而是做之前用实例初始化的someObject = [SomeClass alloc] init];地方someObjectSomeClass

4

3 回答 3

5

Just for clarity when you say "What happens if I call [alloc] init] on an object..." your terminology is wrong.

The following line:

NSMutableArray* someArray = [[NSMutableArray alloc] init];

Reads in English:

"Send the alloc message to the NSMutableArray class object, then send the init message to the object returned from the first message, then store the object returned from init into the pointer variable named someArray."

I say that to emphasize the fact that you're not "calling alloc/init" on an existing object, you're making a new object, and storing a reference to this new object over the reference you had to the previous object. Since you no longer have a reference to that previous object, you've lost the ability to properly release its memory, so yes, you'll leak it.

于 2012-09-18T18:21:47.990 回答
4

对了,会漏的。使用 NSMutableArray insertObject:atIndex‎:

于 2012-09-18T18:16:53.930 回答
1

There are a couple of ways that come to mind to do what I think you want. A sort of clumsy one is to put as many [NSNull null] objects into the array as you need so that it's filled up to the spot where you need to add the new object. Then you would replace an existing NSNull if you were storing your own object.

Probably a better approach is to use a dictionary instead of an array and turn your index value into a key.

于 2012-09-18T18:20:06.887 回答