Search code examples
objective-creferencecountmallocnsmutablestring

how many reference count increase


i now this is a silly question, but i still have some poor understanding about this case. It is about memory management and reference count, i have some doubt about how many reference count will increase if i use copy, alloc, and mutable copy. This is the code i have :

This is myController.h :

#import <UIKit/UIKit.h>


@interface myController : UIViewController {
NSMutableString *mutableStringCode;
}
@property (nonatomic, copy) NSMutableString *mutableStringCode;
@end

and this is myController.m

#import "myController.h"


@implementation myController

-(void)viewDidLoad{
    mutableStringCode = [[NSMutableStringCode alloc]init];
    [self refresh];

}


-(void)refresh{
    NSMutableString *myFileContents = [NSMutableString stringWithContentsOfFile:localPath encoding:NSUTF8StringEncoding error:&error];

    mutableStringCode = [myFileContents mutableCopy]; 

    //another code

    myFileContents = nil;
}


-(void)dealloc{
    [mutableStringCode release];

    [super dealloc];

}

@end

in this code, i have some doubts : 1. how many reference count increase in that mutableStringCode ? 2. is it a true way to set mutableStringCode property using copy not retain? 3. am i still have to alloc that mutableStringCode after i set it copy on property?

can some body describe it to me?? Thank you


Solution

    • If you simply create an instance of the myController class, and then release it, everything will be fine. mutableStringCode will be created in viewDidLoad (if it will be called) and released in dealloc. It happens because alloc retains object.
    • Every time you call refresh, these things happen:
      • you create autoreleased mutable string myFileContents.
      • you copy it to mutableStringCode, retaining it (copy retains object).

    The main problem I see here is that during refresh you are not releasing already created mutableStringCode. So it stays retained in memory (it is usual memory leak).

    You can try to catch these types of memory leaks with Analyse or with Instruments' Leaks tool.