简体   繁体   English

iPhone内存管理和阵列

[英]iphone memory management and arrays

I'm still trying to wrap my head around iphone memory management. 我仍在努力围绕iPhone内存管理工作。 I have checked this with leaks but I want to make sure. 我已经检查了泄漏情况,但我想确定一下。 Is this free of leaks? 这没有泄漏吗?

NSMutableArray *array = [[NSMUtableArray alloc] init];
NSMutableString *str = [[NSMutableString alloc]];

[str appendstring:@"hi"];

[array addObject:str];

[str release]; //this is the bit I am most concerned about


...some processing of array occurs...

[array release];

Assuming your second line is actually this: 假设您的第二行实际上是这样的:

NSMutableString *str = [[NSMutableString alloc] init];

Then yes, this is free of leaks. 然后,是的,没有泄漏。 When you add the string to the array, the array takes an ownership interest in the string, so the subsequent statement where you release your ownership of it is fine. 当您将字符串添加到数组时,该数组会对该字符串具有所有权权益,因此在随后的声明中release该字符串的所有权就可以了。 It still exists in the array as expected. 它仍然按预期存在于数组中。

When you release the array, it will take care of cleaning up its own references, including the one pointing to the string you put in it. 释放数组时,它将负责清理自己的引用,包括指向您放入其中的字符串的引用。

RULE OF THUMB, YOU MAY WRITE THIS ON STICKY NOTE AND STICK IT ON YOUR DESK 大拇指规则,您可以在便利贴上写上此贴,然后在您的桌面上贴上

If you alloc, new, init or copying than you are the owner :) 如果您是所有者,则分配,新建,初始化或复制的内容是:)

You have to release it! 您必须释放它! no one will clean up for you. 没有人会为您清理。

** Example : **示例:

NSString *releaseMeLaterPlease = [NSString initWithString....];

If you create any other way such as in Example assume "bag" is some array, 如果您以示例中的方式创建其他方式,则假定“ bag”是某个数组,

NSString *dontReleaseMe = [bag objectAtIndex:0];

now, dontReleaseMe isn't create by alloc, new, init or copy so you don't release them. 现在,dontReleaseMe不是由alloc,new,init或copy创建的,因此您不会释放它们。 Some one will do it. 有人会做。


If you use autorelease after alloc and init than, OS will take care of releasing it. 如果在alloc和init之后使用autorelease,则OS将负责释放它。


MOST IMPORTANT: Now developer doesn't have to worry about these stuff!!! 最重要:现在,开发人员不必担心这些问题!!! Hoooooray! Hoooooray! Automatic Reference Counting is on from iOS5 从iOS5开始自动引用计数

However it is good to learn as not all devices has iOS5 :) 但是,最好学习一下,因为并非所有设备都具有iOS5 :)

Good luck! 祝好运!

quixoto answered the question, but just for the sake of being explicit, here's what's going on with regard to memory management in your code on each line: quixoto回答了这个问题,但是只是为了明确起见,这是关于每一行代码中的内存管理的情况:

NSMutableArray *array = [[NSMUtableArray alloc] init];  //array retain count = 1
NSMutableString *str = [[NSMutableString alloc]]; //str retain count = 1

[str appendstring:@"hi"];

[array addObject:str];   //str retain count = 2

[str release]; //str retain count = 1

...some processing of array occurs...

[array release]; //array retain count = 0 & str retain count = 0 .. objects will be removed from memory.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM