simple question, I think...

Discussion in 'iOS Programming' started by MACloop, Feb 18, 2010.

  1. MACloop macrumors 6502

    May 18, 2009
    perhaps is this kind of a trivial question, but I am a bit confused about the way to create an object-class and to use memory-management in a proper way. The reason for my question is that I have seen many different ways (in tutorials on the web/ in books etc) to do this. If I have an object, say a car and I want to use this object in some of my viewControllers to show alot of different cars, is this the right way to do it:

    [COLOR="Red"]in car.h:[/COLOR]
    NSString *carTitle;
    @property(nonatomic, retain) NSString *carTitle;
    [COLOR="Red"]in car.m[/COLOR]
    @synthesize carTitle;
    - (void)dealloc{
        [carTitle release];
        [super dealloc];
    [COLOR="Red"]in the viewcontroller.m[/COLOR]
    [COLOR="SeaGreen"]//create a car object[/COLOR]
    Car *theCar = [[Car alloc]init];
    theCar.carTitle = @"My test car";
    [COLOR="SeaGreen"]//save all the objects in an array[/COLOR]
    [carArray addObject:theCar];
    [theCar release];
    [COLOR="SeaGreen"]//later on - show it in for ex. a modal view when the user clicks on a table cell[/COLOR]
    modalCarView =  [[CarModalViewController alloc] initWithNibName:@"CarModalViewController" bundle:nil];
    modalCarView.title = [carArray objectAtIndex:indexPath].title;
    [self.navigationController pushViewController:modalCarView animated:YES];
    [modalCarView release];

    My Questions:
    What about retaining the carTitle in this way? Are there risks with it? Is it correct to release it in the dealloc method?
    What about the alloc/init of the carObject? And the release?
    Is it ok to use @synthesize here? No need for manually programming setter/getter methods? Is the variable not globla in a " not so good" way by doing this?

    I really want to understand this in order to create non-leaking apps and most of all apps not crashing all the time because of "over-releasing" the objects.

    Thanks in advance!
  2. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    The only risk is that the string is mutable and could be changed while it's in your object. In most cases properties for strings should be copy, not retain.

    Yes. You must balance the retain in the setter with a release. It's the same if it's a copy property.

    Looks normal. You might want to write an initWithTitle: method for the class.

    No need for manually programming the getter/setter in the case where the property is a simple ivar like this.

    The setter is public, the ivar isn't. You could make it readonly if you want to prevent other classes from setting the value but your use of the setter from your view controller suggests that's not what you want.

Share This Page