[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now


Memory Management: Objective C

Posted on 2010-08-17
Medium Priority
Last Modified: 2013-11-25
I was a programmer back in the low level days but since then I have used mainly vba to customise office apps. I am now turning my mind to iPhone apps and, therefore, objective-C.

Please can someone explain to me in just-a-paragraph-or-two why and when I have to "count" memory with statements like retain and release.

Why and when do I have to increase the retain count?
Question by:offshorewindinwinter
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 5

Expert Comment

ID: 33460338
Objective-C keeps track of the 'retain count' that an object has - that is, the number of other objects that reference it. If an object has a retain count of 0 or less, that object is considered 'unreferenced', and it's destructors will be called to tear the object down and dealloc the memory. Calling 'release' will trigger this immediately if it's retain count goes to 0 or less.
You may also see references to 'autorelease': Autoreleasing an object tells the runtime that you're releasing the object, but not until the next iteration of the runloop. You quite often get objects returned by class methods of Cocoa objects that create new instances, and it's a convenience to have that object returned 'autoreleased', such that it only lives until it is out of scope. If you wish to use the object (message it) outside of the scope where it's created, you would call [obj retain] to increase the retain count by one and keep the object alive.

Author Comment

ID: 33466832
Thank you RaddishloW

Like all good programmers I am used to modularizing my code with lots of functions/subroutines. I rarely have the need for variables to persist outside the life of these routines. VBA releases all variables at the end of each subroutine automatically and I am careful to release all object variables at the end of each routine. If I do need a variable to persist I declare it as global.

How is this different in objective-C? Is this idea of retaining something like global variables.

Can you give me a concrete example of when I will use retain/release.

Thanks for your help, Neil.
LVL 33

Expert Comment

ID: 33467455
If you are going to use simple types such as int or char, or a bit more complicated: a structure, this rule still works.
If you will work with the objects, you have to forget about your VB experience. Objective-C: the first word here is Objective, so you have to use the Object-Orient design in your programs.
I have to say that on 64-bit Mac OS X, in new Objective-C, this memory management story is trivial - there is GC. Garbage collection is not available on iOS.

iPhone Programming Part 2 : Objective C Memory Management

iPhone memory management - a brief introduction

I can formulate "my rules" for you :), but these guys has made it better.

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Author Comment

ID: 33493028
Can you give me an example please
LVL 33

Expert Comment

ID: 33493048
Example of what?


Author Comment

ID: 33496468
I understand that when you alloc you have to release. I'm just not sure why you would up the retain count by using retain. Saying this another way I'm not sure why you want to set the retain count to 2 or more. An example of this would be very helpful. Cheers
LVL 33

Expert Comment

ID: 33496555
You cannot set a retain counter to 2. You simply call retain when you need an object. It increases the counter by 1. You release the object when you don't need it.

I came from the Windows world and there is a COM technology. There is so call IUnknown interface that has AddRef and Release methods. All other interfaces are derived from this IUnknown. So I got this retain/release easily.

Think about it so: each object in Objective-C has an internal counter. When you create an object this counter is 1. When you immediately release this object (call release method), the counter becomes 0 and the object is automatically destroyed.

Here is the main idea: you don't delete the object, you call release and this release decreases this internal counter. The object will be deleted automatically if the counter is 0.

In order to avoid this auto destroy of the object, you call retain method - it increases the counter. And so the name is retain counter.

For your original question, in an extremely simplified form:
1. If you call 'retain' for an object, you have to call 'release'.
2. If you created an object with 'alloc' and then 'init', you have to call the 'release' in the end.

All that is correct for iPhone projects. On 64-bit Mac OS X (10.6, Snow Leopard), in Objective-C projects, we do worry about that. There is garbage collection already.


Author Comment

ID: 33563677
I thank you for these comments and I'll forgive you if u don't want to persevere with me but my question still remains. Why do I need to retain an object and can you give me a short example of code where this needs to be done. Listen I can add one to one to get two and i can even subtract. I get that an object will be destroyed when the count gets to zero.

You know when you are trying to get a new concept you need to ask "but why" and "can you give me an example". Is it something like this?

So I reference an object and show the information on the screen. I then navigate to another screen where a second instance of the object is read and displayed. Do I add a retain to this second call and a release when I no longer need either screen. Yes?

Is it that space for this object (as opposed to a number) is has the possibility of hogging a lot of memory and it needs to be released ASAP even if I may need to use the space later? Is it that space is soooo tight on the iPhone that I need to be really tidy even if it means reallocating the space later in the app.

Is it that with the human doing the managing memory can be released (and re-used) much quicker?
LVL 33

Accepted Solution

pgnatyuk earned 1000 total points
ID: 33564149
Probably, I do not know the theory good enough to explain everything for you.
If it is not a spelling error, you don't understand the objects in Objective-C. For example, you say "... where a second instance of the object is read and displayed." :(

Second instance is the second instance. It is another object and it has its own counter.

In Objective-C program you use pointers: it is always NSString*, UITextField*. You do create an object (an instance of a class) but you receive the pointer to that instance:
NSString* str = [NSString stringWithFormat:@"%@", @"Hello"];

'str' is the pointer. This line created new object, but you have a pointer to this object.

When you pass this string to another method, you pass the pointer to this string. Now, imagine, that we are talking about a multithreaded application. We created a string and pass it to another method. If there is another thread running and this thread will use this pointer? For example, simply read this string and display it.

If in the first thread (where we created the string) the string object will be destroyed, it will cause a crash in the second thread displaying the string. So when we pass this pointer to the string to another method, we call 'retain' to be sure that the object will be not destroyed.

You decide when you need 'retain' or 'release'. I'd say we cannot expect that the memory will released immediately when we call release for an object. Firstly, because we do not know, maybe, the retain counter of that object is not 0.

You formulated the main rule: release the object when you don't need it.

Objective-C is the C. You can use low-level memory management if you need. Same way as you do it in C.

I think, you need to read the real books and documentation if you need to understand such questions as memory management. I've posted here few links. It's a beginning.

Author Closing Comment

ID: 33567041
An A for your time and persistence. Thank you.
LVL 33

Expert Comment

ID: 33567935
You are welcome

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Let me explain this picture a little bit.  First, in case you haven't already guessed, you are looking at my 2 phones, an Android Samsung Galaxy S5 on the left and an iPhone 5 on the right.  They are on their respective cradles on my desk.  But, you…
After hours on line I found a solution which pointed to the inherited Active Directory permissions . You have to give/allow permissions to the "Exchange trusted subsystem" for the user in the Active Directory...
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

650 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question