开发者

Memory Leaks in Objective-C / Arrays

开发者 https://www.devze.com 2023-03-09 15:54 出处:网络
I\'m looking at someone\'s code and I know the general rule is if you have alloc/init, you need to release that memory.He uses a lot of NSMutableArrays, alloc/inits them, but does not release them.Can

I'm looking at someone's code and I know the general rule is if you have alloc/init, you need to release that memory. He uses a lot of NSMutableArrays, alloc/inits them, but does not release them. Can I simply send the autorelease message to the array that gets created if I do not see any other release/autorelease message getting sent to that array? I basically don't want to get his code to crash and stop working either :P.

With NSMutableArrays, when you send the message addObject and the object in that array increases its retain account, if that array gets released, but the object never gets sent a rele开发者_StackOverflowase or removeObject from the array, is that also a memory leak? Thanks.


You need to either -release or -autorelease anything you -retain, +alloc, -copy, +allocWithZone: or -copyWithZone:. (And, if you retain something twice you also need to release it twice.)

When an NSMutableArray (or NSArray, NSSet, or NSDictionary and mutable subclasses) object is dealloc'd (retain count reaches zero), it releases anything it contains. When you add an object to an NSMutableArray, the array retains the object (it does not copy it like some people claim).

I highly recommend the Memory Management Programming Guide to both you and the someone you referred to in the question.

I hope this answer helps you and someone. Good luck. :)


Also, enable the Clang Static Analyser in the build settings. This will tell you at compile time when a leak is going to happen (and much, much more). In fact, it's the first thing I always do when I start a new project. The analyzer never lied to me.


NSArray and NSMutableArray release all of their objects when they are destroyed, so if the array is managed properly with retain and release (or autorelease) the objects within will not be leaked. But if there are arrays that are never released, they will leak, along with everything inside them.

Without seeing the code, it's hard to advocate for just adding autoreleases everywhere, but for arrays that are used only in the context of a single function (and not assigned to ivars or static variables), the answer is yes, they should be autoreleased. Or more idiomatically, create them with methods like +arrayWithCapacity, which returns an object that has already been added to the autorelease pool.


It is general practice to release all the objects you initialize. But in your case, releasing the array should release all objects as well.

But it all depends on how you are using your objects !!!

0

精彩评论

暂无评论...
验证码 换一张
取 消