Objective-C:在另一个对象的init中分配对象(内存管理)

Objective-C:在另一个对象的init中分配对象(内存管理)

问题描述:

在我的 .h文件中我有:

NSMutableArray *myArray;
@property (nonatomic, retain) NSMutableArray *myArray;

我的 .m文件看起来基本上都是这样的:

My .m file looks basically like this:

@synthesize myArray;

- (id) init {
    self = [super init];

    if (self != nil)
    {
        self.myArray = .... ? // here I want to create an empty array
    }

    return self;
}

- (void) dealloc {
    [self.myArray release];

    [super dealloc];
}

我不确定的是 init 。

1)

self.myArray = [[NSMutableArray alloc] init];

2)

NSMutableArray *tmp = [[NSMutableArray alloc] init];
self.myArray = tmp;
[tmp release];

解决方案1对我来说似乎不对,因为我的 @property (保留)设置我在设置self.myArray时自动增加保留计数器,但另外由于 [NSMutableArray alloc] $我已经有+1保留 c $ c>然后以该对象的保留计数为2结束,但只在 dealloc 中释放一次。因此第二种解决方案对我来说似乎更正确,即使它很麻烦。

Solution 1 doesn't seem right to me, because of my @property (retain) setting I automatically increase the retain counter when setting self.myArray, but additionally I have already a "+1 retain" due to the [NSMutableArray alloc] and then ending up with a retain count of 2 for that object, but only releasing once in the dealloc. Thus the second solution seems more correct to me, even though it is cumbersome.

我也想知道 self.myArray = ... 实际上与 [self setMyArray:...] 相同,因此会增加保留计数。

Also am I wondering if self.myArray = ... is actually the same as [self setMyArray:...] and thus does increase the retain count.

更新

我实际上找到了答案(甚至更多细节)这里,以防有人有兴趣阅读更多内容。

I actually found the answers (and even more details) here in case anyone is interested in reading more.

self.myArray = 完全相同[self setMyArray:...]

但是你可以做 myArray = [[NSMutableArray alloc] init]; 最终保留计数为1,并且完全合法。

You could however do myArray = [[NSMutableArray alloc] init]; which would end up with a retain count of 1 and would be totally legit.