Setting an object nil versus release+realloc

前端 未结 6 910
隐瞒了意图╮
隐瞒了意图╮ 2021-02-15 01:34

This is not a garbage collected environment

I have a class instance variable which at some point in my runtime, I need to re-initialize with a different data set than it

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-15 02:10

    The first code block is fine. However, the second block does not leave you with an array you can use so it is not sufficient. Half correcting that block, I think you mean:

    myArr = nil;
    myArr = [[NSMutableArray alloc] init....];
    

    However, this does not accomplish what you want either because you are not releasing myArr. If you have synthesized a setter for myArr, then you can get the release behavior you want from setting to nil, by using the setter (self.myArr) instead of accessing the pointer directly (myArr). Correcting your second block fully:

    self.myArr = nil;
    myArr = [[NSMutableArray alloc] init....];
    

    Now we have equivalent code examples, one using setter with nil to release, the other not. They are the same.

    If myArr is a mutable array as in these examples, the most efficient method is to use removeAllObjects, avoiding all the work of releasing memory only to claim it back:

    [myArr removeAllObjects];
    

提交回复
热议问题