Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is retainCount in Objective-C?

I have a UITableView as my first screen with a UINavigation controller.

In my first screen I NSLog(@"Home Screen retain Count=%d",[self retainCount]); and it logs 6 in when its viewDidLoad is called.

Is this correct?

like image 639
Rahul Vyas Avatar asked Jul 30 '09 11:07

Rahul Vyas


People also ask

Why retainCount should never be used in shipping code?

You should never use -retainCount , because it never tells you anything useful. The implementation of the Foundation and AppKit/UIKit frameworks is opaque; you don't know what's being retained, why it's being retained, who's retaining it, when it was retained, and so on.

What does a retain count represent in ARC?

Retain Count represents number of owners for a particular object. It is zero till object does not have any owners. Increase in one ownership claim will cause retain count to increase by 1 and decrease will cause it to decrement by 1. Example: - Class A object is created using alloc/init and retain count is 1.

What is memory Management in Objective C?

Advertisements. Memory management is one of the most important process in any programming language. It is the process by which the memory of objects are allocated when they are required and deallocated when they are no longer required.

What is swift Retain count?

Every object in Swift – an instance of a class – has a property called retainCount. When the retain count is greater than zero, the object is kept in memory. When this retain count reaches zero, the object is removed from memory.


2 Answers

The retainCount is the number of ownership claims there are outstanding on the object.

You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message. All of these increment the retainCount.

You relinquish ownership with using “release” or “autorelease”. These decrement the retainCount.

However you should never pay any attention to the value of retainCount, it is at best confusing, at worst misleading. Simply follow the memory management rules - take ownership when you need to keep a reference to an object and relinquish ownership when you are finished, and you wont have a problem.

If you are looking at retainCount, you are going about things the wrong way, and you will simply confuse yourself further.

like image 55
Peter N Lewis Avatar answered Oct 03 '22 18:10

Peter N Lewis


It sounds fine. Why would it be wrong?

In general, trying to determine things from the retain count is a bad idea. There are no rules about the amount of times you can retain an object. The only rule is that each retain must be balanced with a release.

like image 23
Tom Dalling Avatar answered Oct 03 '22 20:10

Tom Dalling