glenn sayers
glenn sayers

Reputation: 2414

Memory management, should I be retaining?

If I declare an NSString in my header file as follows:

{
  NSString *testString; 
}
@property(nonatomic,retain) NSString *testString;

Then synthesize the string in my .m file, what is the correct way to initialise it? If I don't write: self.testString = [[NSString alloc] init];

then the it is never initialised, but if I do, then isn't the string being retained twice? Or should I initialise it some other way, such as:

self.testString = [NSString stringWithFormat:@"%@, sampleText];

Upvotes: 2

Views: 88

Answers (4)

Simon Germain
Simon Germain

Reputation: 6844

It seems that you declare an variable called testString in your .h and you also create a property that retains.

You can either use this:

self.testString = [NSString string];

or you can use

testString = [[NSString alloc] init];

Defining the variable through the property will cause it to be retained, that's why you declared it as (nonatomic, retain). Defining the variable through the declaration won't take those arguments into consideration. Here's a quick rule of thumb about retaining.

Using your code as a base:

self.testString = [[NSString alloc] init]; // Retain count = 2
self.testString = [NSString string];       // Retain count = 1
testString = [[NSString alloc] init];      // Retain count = 1
testString = [NSString string];            // Not retained at all.

Upvotes: 1

ksh
ksh

Reputation: 1904

First of all @property (nonatomic, copy) NSString *testString to avoid mutability bugs. Second - if you want just a string without leaks:

self.testString = [NSString string];
self.testString = [[[NSString alloc] init] autorelease];
self.testString = [NSString stringWithFormat:@"%@", text];

these are all valid options.

Upvotes: 0

user971401
user971401

Reputation:

You are correct, the former will over retain the object.

Use the second form instead.
If you had to use the ivar directly however, you need to retain the object :

testString = [[NSString stringWithFormat:@"%@, sampleText] retain];

Upvotes: 2

Andrey Zverev
Andrey Zverev

Reputation: 4428

self.testString = [NSString stringWithFormat:@"%@, sampleText]; or self.testString = [NSString string]; is correct; self.testString = [[NSString alloc] init]; will cause over-retaining.

Consider using ARC (Automatic Retain Counting) for you project. With ARC the compiler takes care of retain counts so you don't have to, in fact aren't allowed to. There is a refactoring that will convert a current project.

Upvotes: 1

Related Questions