Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Apple > Operating Systems

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Retain Count

Calling retain on an object is not the only way to increment the retain count. Whenever a new object is created, it is a safe bet that the process of creation will increment the retain count on that object. Calling either copy or init on an object will increment the retain count on that object (or the copy as appropriate).

As an example, take the following piece of code:

- (NSString *)formattedName {
 NSString *initString = [[NSString alloc] initWithFormat:@"[%@]", name];
  NSString *tempString = [NSString stringWithFormat:@"[%@]", name];
  NSString *copyString = [tempString copy];
  return fname;
}

In this example, the retain count on initString and copyString is 1. However, the retain count on tempString is 0. The reason for this difference is because of the way they are instantiated.

Because initString is created by using the init method, its retain count is incremented. As part of the init process, the object's retain count is automatically incremented.

As for tempString, it is using a convenience method that does not increment the retain count. Technically, the retain count is incremented but it is also autoreleased, which will be discussed in the next section.

The final NSString pointer is created using the copy method inherited from NSObject. Per Objective-C's documentation, this method returns a copy that has its retain count incremented.

Here's a general rule of thumb: If the object is created using either a copy method or an init method, its retain count has been incremented. Otherwise, the object has not been retained and a call to the object's retain method is necessary to keep a long-term reference to it.

  • + Share This
  • 🔖 Save To Your Account