IOS7 memory release issue

隐身守侯 提交于 2020-01-16 13:50:53

问题


My IOS program is not ARC, code like this:

in the .h file i define five variables:

{
    UILabel *label1,*lable2;
    UIView *dwView;
    NSMutableArray *wordsArray;
}

the code in the .m file like this:

- (void)viewDidLoad{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    viewArray=[[NSMutableArray alloc]init];
}

-(void)QuestionA{
    dwView=[[UIView alloc] initWithFrame:CGRectMake(20, 50, 975.0, 620)];

    label1 = [[UILabel alloc]initWithFrame:CGRectMake(10.0, 160.0, 950.0, 170.0)];
    label2 = [[UILabel alloc]initWithFrame:CGRectMake(30.0, 160.0, 950.0, 170.0)];

    [dwView addSubview:label1];
    [dwView addSubview:label2];

    [self.view addSubview:dwView];
    [viewArray addObject:dwView];

    [lable1 release];
    [lable2 release];
    [dwView release];
}

before I turn to another activity I log out the retain count of those variables:

{
    [lable1 retainCount] ---> 2
    [lable2 retainCount] ---> 2
    [dwView retainCount] ---> 3
}

So: I wonder why it like this, and how can I release the retain count to 0?


回答1:


Presumably these are the retain counts before you call "release" at the end of your routine.

Calling the traditional "alloc" / "init" starts the newly instantiated object off with a retain count of 1. When you add dwView as a subview to a parent view, that increments the retain count. When you add dwView to the array, that also increments the retain count. Hence 3 there.

Same for the labels, you've added them as subviews, so that increments the retain count by 1 for each (giving you a retain count of 2).

The object will be released when the retain count hits zero (e.g. for your "dwView", that'll be when "self.view" is dealloc'd and when the "viewArray`" gets released).




回答2:


If use ARC , you may try @autorelease{} Every time, addview will make a copy of the view.




回答3:


it has been mentioned many times in apple docs that never go by retain count.

if you are allocating for some memory make sure you call release on that.

its left to system to release that memory chunk and system will do that when retain count reaches zero

below is what apple docs says

Important: There should be no reason to explicitly ask an object what its retain count is (see retainCount). The result is often misleading, as you may be unaware of what framework objects have retained an object in which you are interested. In debugging memory management issues, you should be concerned only with ensuring that your code adheres to the ownership rules.



来源:https://stackoverflow.com/questions/20390581/ios7-memory-release-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!