Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak when using NSString inside for loop

I have 100 images in my resource bundle named like image1.jpg,image2.jpg. Basically what i am trying to do is create path names to those images dynamically inside a for loop.
While testing in simulator,the images loaded fine and the app did not crash.But while testing the app with instruments i was shocked to see the heavy memory leak that was happening while i was creating the path1 object.

     I am pasting  the entire method here for reference

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

    self.arrayImages = [[[NSMutableArray alloc] init] autorelease];      

    for(int i=1 ; i<100 ; i++){            

        NSString *str = [NSString stringWithFormat:@"Century%d",i];
        NSString *path1 = [[NSBundle mainBundle] pathForResource:str ofType:@"jpg"];            
        [self.arrayImages addObject:path1];        
    }                        
}
return self;

}

As i have not made use of any alloc inside the loop i dont have any ownership and hence no right to release the object.What is the reason for this memory leak??

Kindly explain the problem and provide the necessary solution in order to fix it..

As always,any help is highly appreciated..

like image 974
Mr.Anonymous Avatar asked Feb 13 '26 18:02

Mr.Anonymous


2 Answers

arrayImages is retaining path1, and so if you do not release arrayImages it will leak. How are you creating arrayImages, and are you releasing it anywhere?

Edited based on comments:

Make sure you release arrayImages in your -dealloc method like so: [arrayImages release]; (note the lack of self).

like image 194
jrtc27 Avatar answered Feb 16 '26 06:02

jrtc27


There is no leak in the code you've shown.

There are (at least) two possibilities:

  1. You have a leak in code you didn't paste into your question
  2. Everything is fine and Instruments gave you a false-positive

Your loop will create a lot of autoreleased variables. These won't be deallocated until after the loop has finished, but that's how it's supposed to work.

like image 42
Stephen Darlington Avatar answered Feb 16 '26 08:02

Stephen Darlington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!