简体   繁体   中英

iphone memory management and arrays

I'm still trying to wrap my head around iphone memory management. 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. 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,

NSString *dontReleaseMe = [bag objectAtIndex:0];

now, dontReleaseMe isn't create by alloc, new, init or copy so you don't release them. Some one will do it.


If you use autorelease after alloc and init than, OS will take care of releasing it.


MOST IMPORTANT: Now developer doesn't have to worry about these stuff!!! Hoooooray! Automatic Reference Counting is on from iOS5

However it is good to learn as not all devices has 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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