Search code examples
iossubclassing

ios base page view controller value allocation


Im using a Base view controller for some other view controllers,

Im making it the base as I have 4 to 6 of other view controllers that will be showing the same label and image...

so I tried to make this base page and subClass the other ViewControllers,

my doubt is that if I leave the dealloc for the strings that contain the value for the label and other string, when dealloc is called for that page, then I get an exception

pointer being freed was not allocated

but I dont want just to comment out the deallocs for the labels,

so What im i doing wrong, missing?

here the BasePage

#import "BasePage.h"
@implementation BasePage
@synthesize titleString = _titleString;
@synthesize justifyTitleString = _justifyTitleString;

- (void) dealloc {
[_titleString dealloc];      
[_justifyTitleString dealloc];
[super dealloc];
}
- (id)initWithParams:(NSString *)title :(NSString *)justifyTitle
{
self = [super init];
if (self) {
    self.titleString = title;
    self.justifyTitleString = justifyTitle;
}
return self;
 }

my app uses a navigation controller, so when I call a page i use:

   CentresVC *centresVC = [[[CentresVC alloc]initWithParams:[NSString stringWithFormat:@"Centre  %d", indexPath.row]:@"center"]autorelease];
[self.navigationController pushViewController:centresVC animated:YES];

and pop the views when navigating back,

  • So I have the doubt of when using
 [_titleString dealloc];      
   [_justifyTitleString dealloc];

where the pointer for those labels get saved?, and if i just commented out wich doesnt seem nice, would i get then a memory leak that would crash?

how to fix this?

thanks!


Solution

  • As Richard said, you shouldn't be calling other objects' dealloc method. Ever.

    If titleString and justifyTitleString are retained/strong properties, then this version below would work. Assuming that no other objects had retained titleString and justifyTitleString, their retain counts would go to 0, and their dealloc methods would be called automatically.

    - (void) dealloc {
        [_titleString release];      
        [_justifyTitleString release];
        [super dealloc];
    }
    

    This next option would work too, since the synthesized setter for a strong/retained property sends release to the old value of the property before assigning the new one. Also, this would be preferred if you had overridden your setter to do additional cleanup of the old value.

    - (void) dealloc {
        self.titleString = nil;
        self.justifyTitleString = nil;
        [super dealloc];
    }
    

    Finally, if you were using ARC, and you didn't need additional cleanup like in the second case above, you wouldn't need to override dealloc at all. But if you did need to override dealloc, you would omit [super dealloc] since that would be provided automatically by the compiler.