views:

25

answers:

2

What is the preferred and/or correct way to release an NSMutableString (or any other class for that matter) instance and assign a new instance to the same variable in Objective-C on the iPhone?

Currently I'm using

[current release];
current = [NSMutableString new];

but I understand that the following works, too.

NSMutableString *new = [NSMutableString new];
[current release];
current = [new retain];
[new release];

The variable current is declared in the interface definition of my class and gets released in dealloc.

A: 

Both versions should work equally well. Which means I'd go with the first one - fewer lines of code.

Thomas Müller
A: 

If you're thinking about handling instance variable I'd suggest using property for that - in you class interface declare:

// MyClass.h
@interface MyClass {
   NSMutableString* current;
}

@property (nonatomic, retain) NSMutableString* current;
@end

And then let compiler generate setter and getter methods for you automatically with desired memory management behaviour:

// MyClass.m
@implementation MyClass

@synthesize current; // Tell compiler to generate accessor methods
...

The generated setter method will release previous "current" value and retain the new one. You'll still need release it in your dealloc method.

To access you variable via property you should use .:

self.current = [NSMutableString string]; 

This is equivalent to calling [self setString:[NSMutableString string]] (setString method will be generated automatically).

Also as you're dealing with mutable string here it may be worthwhile to use copy atribute for property instead of retain.

Vladimir
Thanks for your answer, much appreciated.I had been thinking about using properties but I was assuming that they are always public. Turns out I was wrong (http://swish-movement.blogspot.com/2009/05/private-properties-for-iphone-objective.html), so I'll most likely switch to properties.
David Gonrab