TeaCupApp
TeaCupApp

Reputation: 11452

Memory management dilemma, Objective -C

I have been testing different features of Objective -C and reached topic which deals with memory management. Apparently upon reading few documents it seems memory management is a very strict in order to build well functioned application.

Now as per my understanding, When we allocate a memory an object's retainCount will become 1. However Something I wrote for learning purposes and it is giving me abnormal retainCount

It might be abnormal number for me, But people who's knows under the hood, Could you please explain how did I get this retainCount and what will be the best way to release it.

Code which has abnormal retainCount,

Object name is : ...(UISlider *) greenSender...

-(IBAction) changeGreen:(UISlider *)greenSender{
    showHere.textColor = [UIColor colorWithRed:red.value green:greenSender.value blue:blue.value alpha:1.0];
    NSLog(@"retainCount %d",[greenSender retainCount]);
}

Has reatainCount, just after executing my code.

enter image description here

A short explanation will give me a hint, And external reading resources would be appreciated. Thanks

Upvotes: 1

Views: 123

Answers (2)

Jilouc
Jilouc

Reputation: 12714

Do not trust/rely on retainCount. Really.

From Apple:

Important: This method is typically of no value in debugging memory management issues. Because any number of framework objects may have retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number of deferred releases on an object, it is very unlikely that you can get useful information from this method.

Upvotes: 5

Adam Rosenfield
Adam Rosenfield

Reputation: 400156

Do not rely on retain counts. They should only be used as a debugging tool. The reason is that if an object gets retained and autoreleased, its effective retain count has not changed, but its actual retain count has increased by one. It will be released at some point in the future when the autorelease pool drains. Therefore, you cannot rely on the retain count for knowing whether the object has been managed properly or not.

A large retain count such as 8 may indicate a programming bug (such as retaining it too many times), but it could also just be a sign that it has been retained and autoreleased a large number of times, which, although curious, could be perfectly valid.

Upvotes: 5

Related Questions