Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

cthesky

macrumors member
Original poster
Aug 21, 2011
91
0
Hi,

I am newbie of develop Iphone Application. I am quite confuse with the memory management when using objects in my application.

Here is my code:

(I have a CarDao class to access database; a car entity which has a attribute named as carName).
Code:
-(void)displayCar
{
    CarDao * dao = [[CarDao alloc]init];
    
    //Select all cars from database.
    [COLOR="Blue"]NSMutableArray * cars = [dao selectAllCars];  [/COLOR]
     
    if ([cars count]>0) 
    {

        for (int i=0; i<[cars count]; i++) 
        {
            [COLOR="Blue"]Car * car = [[Car alloc]init];[/COLOR]
            car = [cars objectAtIndex:i];

            if (car != nil)
            {
                NSString * carName = car.carName;
                NSLog(@"Car name %@ ", carName);
            }

            [car release];           
        }
    }
    
    [dao release];
}
But, when I trace the memory leaks by using the instruments. It shows the leaked blocks. These leaked blocks is caused by the code in blue color as shown in above. I'm quite confuse because I already release the "car" and "dao" at the end of code but why the memory problem still exists. Or am I doing something wrong in my code. Can someone tell me? Or can someone show me the correct way to write this code? Any comments and suggestions are welcome.

Thanks a lot for your help. :)
 
Last edited:
You're creating a new car object, but on the next line you're assigning the pointer to a different object, so your car object you previously created has no pointer to it. Dont send an alloc init message to the new car, just send it the objectAtIndex instead.
 
You're creating a new car object, but on the next line you're assigning the pointer to a different object, so your car object you previously created has no pointer to it. Dont send an alloc init message to the new car, just send it the objectAtIndex instead.

Hi lee.anderson,

Really thanks for your reply. :) I quite understand what you replied. I have changed my code. Is it correct? Can you give some comments?

Code:
-(void)displayCar
{
CarDao * dao = [[CarDao alloc]init];

//Select all cars from database.
NSMutableArray * cars = [dao selectAllCars];

if ([cars count]>0)
{

for (int i=0; i<[cars count]; i++)
{
[COLOR="Blue"]Car * car = [cars objectAtIndex:i];[/COLOR]

if (car != nil)
{
NSString * carName = car.carName;
NSLog(@"Car name %@ ", carName);
}

//[car release];

}
}

[cars release];
[dao release];
}

And I have a question. That is since I have changed the code for car object to Car * car = [cars objectAtIndex:i];. So is it still need to release "car"? This is because just now I try to release "car", but the application crash when I run it.

Thanks. :)
 
Last edited by a moderator:
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.