Solved

Memory Management: Objective C

Posted on 2010-08-17
11
675 Views
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?
0
Comment
Question by:offshorewindinwinter
[X]
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
11 Comments
 
LVL 2

Expert Comment

by:RaddishIoW
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.
0
 

Author Comment

by:offshorewindinwinter
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.
0
 
LVL 33

Expert Comment

by:pgnatyuk
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.
http://developer.apple.com/mac/library/documentation/cocoa/conceptual/MemoryMgmt/MemoryMgmt.html

iPhone Programming Part 2 : Objective C Memory Management
http://www.gehacktes.net/2009/02/iphone-programming-part-2-objective-c-memory-management/

iPhone memory management - a brief introduction
http://mauvilasoftware.com/iphone_software_development/2008/01/iphone-memory-management-a-bri.html

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


0
Industry Leaders: 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

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

Expert Comment

by:pgnatyuk
ID: 33493048
Example of what?

0
 

Author Comment

by:offshorewindinwinter
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
0
 
LVL 33

Expert Comment

by:pgnatyuk
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.

0
 

Author Comment

by:offshorewindinwinter
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?
0
 
LVL 33

Accepted Solution

by:
pgnatyuk earned 250 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.
0
 

Author Closing Comment

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

Expert Comment

by:pgnatyuk
ID: 33567935
You are welcome
 
0

Featured Post

Secure Your Active Directory - April 20, 2017

Active Directory plays a critical role in your company’s IT infrastructure and keeping it secure in today’s hacker-infested world is a must.
Microsoft published 300+ pages of guidance, but who has the time, money, and resources to implement? Register now to find an easier way.

Question has a verified solution.

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

Suggested Solutions

Are you having trouble connecting or getting your iPhone / Samsung device(s) to sync with Microsoft Exchange Server?   What have you tried?   What haven't you tried?
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.

733 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