tags:

views:

29

answers:

1

Hi,

I have question about allocating and releasing objects:

if I have code like this:

MyObject *object = [[MyObject alloc] init];
NSMutableString *string = [[NSMutableString alloc]initWithString:@"bla"];
object.myString = string;
NSLog(@"retain count: %d",[object.myString retainCount]); //gives me 2
[string release];
NSLog(@"retain count: %d",[object.myString retainCount]); //gives me 1

Than I have exactly what I want. I need just one reference and I have retain count 1

but

if I use

object.myString = [[NSMutableString alloc]initWithString:@"bla"];

my property look like this:

@property (nonatomic,retain) NSMutableString *myString;

one alloc, and one setter method with retain gives me as retain count 2

If I release the object after resignment than the app crashes. I dont know why?

So , do i have to always create an object with a temporary reference, than assign to real reference and release the temp reference like first code?

or is there any other way?

+1  A: 

Yes and no. Generally, this is a common pattern:

// create the object, retain count 1
MyObject *myObject = [[MyObject alloc] init];

// increment the retain count in the setter
self.myObjectProperty = myObject;

// let go of the object before the end of the current method
[myObject release];

You can avoid the release, sort of, by using autorelease pools. More accurately, you indicate that you want the object to be released soon:

MyObject *myObject = [[[MyObject alloc] init] autorelease];
self.myObjectProperty = myObject;

// all done!

With many of the Apple-provided classes, you can use class methods other than alloc/init to get objects that are already autoreleased. Your example could be rewritten as:

MyObject *myObject = [[MyObject alloc] init];
myObject.myString = [NSMutableString stringWithFormat:@"bla"];

A final note: -retainCount is a blunt object. Particularly with NSStrings and other built-in classes, it may return results that are quite different from what you expect. Generally you should avoid it.

Seamus Campbell
Thanks for your reply. I am using objective-c for iphone app development, thats why i generally dont want to use autorelease pool.When I use apple provided classes, i dont use release it is ok.I realy want to knowIs the following code okobject.myString = [[NSMutableString alloc]initWithString:@"bla"];[object.myString release];or do I need release once more?
jourbus
That sequence is fine but unless you're making a whole lot of strings or your app is otherwise a major memory hog I really wouldn't worry about using autoreleased objects here and there. Note that there is one more release you should have, in `-[MyObject dealloc]`. If you have that then you've properly paired your retains and releases.
Seamus Campbell
Thank you very much
jourbus