What is the best way to understand memory management in iOS development?
-
I have been an iOS dev for almost a year now. I am still constantly trying to have a solid foundation of memory management in iOS. What resources (books, videos, tricks, methods)are there to get a good grasp of this concept as it is an integral an important part of iOS development? I have read the memory management documentation from Apple, but it seems to be pretty lengthy.
-
Answer:
Each object has a "retain count" which is increased by calling "retain" and decreased by calling "release". Once the retain count hits 0, the object is released and the memory can be used for something else. You can "autorelease" objects. This means the retain count isn't immediately decreased, but is decreased the next time the current autorelease pool is drained. iOS apps have an event loop in which your code runs. After each iteration of the event loop, the autorelease pool is drained. Any object with a retain count of 0 is released. By default, autoreleased objects are returned by methods that don't begin with new, copy, mutableCopy, retain or init. This means you can use them immediately but if you don't retain them the object will be gone on the next iteration of the run loop. If you fail to release retained objects but no longer reference them then you will have a memory leak, this can be detected by the leaks tool in Instruments. One strategy is to autorelease everything returned by the above named methods and store objects in retain properties (or copy for strings). In your object's dealloc method, set all your properties to nil. Setting a retain/copy property to nil releases the object that it currently points to. As long as you don't have any circular references (avoided by not using retain properties for "parent" objects such as delegates), you will never encounter any leaks.
Brian Collins at Quora Visit the source
Other answers
I was responsible for reducing memory usage on a relatively big app for two months. So I would like to share some resources I found particularly useful to me. Apple Doc: Advanced Memory Management. One of the must-read to understand iOS manual memory management. I agree it's pretty lengthy. It took me a long time to read through and understand it. https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html Apple WWDC Videos: For me, WWDC videos are a quicker way to understand iOS memory management than reading Apple docs. You can access those videos on Apple developer website. WWDC 2013: Fixing Memory Issues. WWDC 2012: iOS App Performance Memory WWDC 2011: iOS Performance in Depth WWDC 2010: Advanced Memory Analysis with Instruments Online Tutorials: http://www.raywenderlich.com/author/rwenderlich's blog. Memory Management in Objective-C Tutorial. http://www.raywenderlich.com/2657/memory-management-in-objective-c-tutorial It's also helpful to understand how to use the memory measurement tools like Allocations and VM Tracker. They provide a hands-on experience about how memory is allocated in your app. I will update this post if I finish my blog about memory management. Hope it helps!
Jingjie Zhan
Don't autorelease stuff on the main thread. That's tantamount to a leak. Run Build & Analyze religiously. Fix warnings. The static analyzer will not catch all of your leaks. Leaks in Instruments won't even catch all your leaks. Use Object Allocations in Instruments on the device, sort by live memory and pay attention both to the total and to the individual blocks. Any objects that stick around across view controller transitions should be investigated. Run it periodically and if possible get your testers to as well. Clean out the URL cache periodically, and definitely on memory warnings. On that note, handle memory warnings. Even if you do nothing, leave the template function in the class with a call to super. Don't leave a lot of hi-res images in memory. You have relatively little RAM on the device and the OS will kill you if you exceed it on older phones. Off-screen images should purged from live memory. Beware of third-party libraries. Ad libraries in particular can be memory sinks and you don't have access to their code to debug. Use iAds (but if you do only ever use one and make sure not to obscure it with UI elements) or AdMob. Delegates should be WEAK references. That means properties with assign, not retain. This is because normally delegates retain the objects that are delegating to them, and if both of them retain each other, you will get what's called a retain cycle and neither will ever release the other. Boom, two leaks. Name your instance variables with camelCase and your locals with under_score. Release all instance variables at the end of the function unless they're already autoreleased when you get them. Release all instance variables, even IBOutlets and ones with properties that specify retain, in dealloc. NEVER forget the call to super in dealloc. Release the old values of instance variables or locals with a retain count greater than zero before you assign a new value Always. If the variable is nil it will eat the release message, and if not then you own it, so you need to release it.
Ben Jackson
Letâs start with retain and release; autorelease is really just a special case once you understand the basic concepts. In Cocoa, each object keeps track of how many times it is being referenced (specifically, the NSObject base class implements this). By calling retain on an object, you are telling it that you want to up its reference count by one. By calling release, you tell the object you are letting go of it, and its reference count is decremented. If, after calling release, the reference count is now zero, then that objectâs memory is freed by the system. The basic way this differs from malloc and free is that any given object doesnât need to worry about other parts of the system crashing because youâve freed memory they were using. Assuming everyone is playing along and retaining/releasing according to the rules, when one piece of code retains and then releases the object, any other piece of code also referencing the object will be unaffected. What can sometimes be confusing is knowing the circumstances under which you should call retain and release. My general rule of thumb is that if I want to hang on to an object for some length of time (if itâs a member variable in a class, for instance), then I need to make sure the objectâs reference count knows about me. As described above, an objectâs reference count is incremented by calling retain. By convention, it is also incremented (set to 1, really) when the object is created with an âinitâ method. In either of these cases, it is my responsibility to call release on the object when Iâm done with it. If I donât, there will be a memory leak. Example of object creation: NSString* s = [[NSString alloc] init]; // Ref count is 1 [s retain]; // Ref count is 2 â silly // to do this after init [s release]; // Ref count is back to 1 [s release]; // Ref count is 0, object is freed Now for autorelease. Autorelease is used as a convenient (and sometimes necessary) way to tell the system to free this object up after a little while. From a plumbing perspective, when autorelease is called, the current threadâs NSAutoreleasePool is alerted of the call. The NSAutoreleasePool now knows that once it gets an opportunity (after the current iteration of the event loop), it can call release on the object. From our perspective as programmers, it takes care of calling release for us, so we donât have to (and in fact, we shouldnât). Whatâs important to note is that (again, by convention) all object creation class methods return an autoreleased object. For example, in the following example, the variable âsâ has a reference count of 1, but after the event loop completes, it will be destroyed. NSString* s = [NSString stringWithString:@"Hello World"]; If you want to hang onto that string, youâd need to call retain explicitly, and then explicitly release it when youâre done. Consider the following (very contrived) bit of code, and youâll see a situation where autorelease is required: - (NSString*)createHelloWorldString { NSString* s = [[NSString alloc] initWithString:@âHello Worldâ]; // Now what? We want to return s, but weâve upped its reference count. // The caller shouldnât be responsible for releasing it, since weâre the // ones that created it. If we call release, however, the reference // count will hit zero and bad memory will be returned to the caller. // The answer is to call autorelease before returning the string. By // explicitly calling autorelease, we pass the responsibility for // releasing the string on to the threadâs NSAutoreleasePool, which will // happen at some later time. The consequence is that the returned string // will still be valid for the caller of this function. return [s autorelease]; } I realize all of this is a bit confusing â at some point, though, it will click. Here are a few references to get you going: Appleâs introduction to memory management. Cocoa Programming for Mac OS X (3rd Edition), by Aaron Hillegas â a very well written book will lots of great examples. It reads like a tutorial. If youâre truly diving in, you could head to Big Nerd Ranch. This is a training facility run by Aaron Hillegas â the author of the book mentioned above. I attended the Intro to Cocoa course there several years ago, and it was a great way to learn. You can read more at my blog at http://scottfaisal.com
Scott Faisal
Related Q & A:
- What is the best way to distribute an audio/video feed from a computer to TVs over existing indoor coax cable?Best solution by Audio-Video Production
- What is the best way to clean LEGO bricks?Best solution by bricks.stackexchange.com
- What is the best way to make UI for an Isometric game in Java?Best solution by Game Development
- What is the best way to calculate a date difference?Best solution by Stack Overflow
- What is the best way to count lines in file?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.