Memory Management: Objective C

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?
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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.
offshorewindinwinterAuthor Commented:
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.
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.

Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

offshorewindinwinterAuthor Commented:
Can you give me an example please
Example of what?

offshorewindinwinterAuthor Commented:
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
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.

offshorewindinwinterAuthor Commented:
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?
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.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
offshorewindinwinterAuthor Commented:
An A for your time and persistence. Thank you.
You are welcome
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.