views:

90

answers:

2

See title. To be more specific, I am trying to return the mutableCopy of an object, however it's returned with a retainCount of 1 and I am worrying that it will leak.

A: 

Hello, Yakattak.

mutableCopy always increment the retainCount of an object. So, if you use retain, copy or mutableCopy you must release in dealloc method.

If you are returning that object you must to use autorelease, like this:

[[[NSString alloc] initWithString:@"Test"] autorelease];

The autorelease pool will release the object for you and there is no need to release in dealloc method.

Hope that helps you.

R31n4ld0_
I understand that, but what if I am returning said object?
Yakattak
Sorry, miss the return part in your question.
R31n4ld0_
+9  A: 

Your method should follow standard memory management procedures. If your method returns an object, but does not contain the words "alloc", "new", "copy", "create", or "retain", then the object should be autoreleased.

If it does contain one of those words, then it should be returned with a +1 retain count.

For example:

//return an autoreleased object, since there's no copy, create, retain, alloc, or new
- (id) doSomethingWithFoo:(id)foo {
  id fooCopy = [foo copy];
  [fooCopy doTheNeedful];
  return [fooCopy autorelease];
}

//return a +1 object, since there's a copy in the name
- (id) copySomethingWithFoo:(id)foo {
  id fooCopy = [foo copy];
  [fooCopy doTheNeedful];
  return fooCopy;
}
Dave DeLong