skylerl
skylerl

Reputation: 4180

What should the retainCount be when returning an object in Objective-C?

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.

Upvotes: 0

Views: 184

Answers (2)

reinaldoluckman
reinaldoluckman

Reputation: 6348

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.

Upvotes: 0

Dave DeLong
Dave DeLong

Reputation: 243146

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;
}

Upvotes: 10

Related Questions