开发者

iPhone object checking to release

I want to check if an object has some count or not Here is my testing code

NSMutableArray  *array=[[NSMutableArray alloc]init];

    if(array)
    {
        N开发者_StackOverflow社区SLog(@"hiiiiiii"); 
    }

CASE-2

NSMutableArray  *array=[[NSMutableArray alloc]init];
    [array release];
    if(array)
    {
        NSLog(@"hiiiiiii"); 
    }

Here in both cases i got same output as printed "hiiiiiii".

Can anyone tell me how will i check if my object need to release or already released.

I know that i should have track of my object's counters but i am at a stage where my code is too much complexed and i need help..

Please help..

ALso tell that how much memory leak is allowed by apple?


There is no way to check if you "should" release an object. Doing something like "if(object)" only checks the pointer to the object. It will return true even if the object it was pointing to was destroyed a long time ago. This is what happens in your second case. The object is destroyed when you call release, but the pointer is still pointing at something, so it returns true. It will only return false if the pointer is set to nil.

However, there is a simple set of rules for calling release. If you ever call "alloc", "new", "copy", "mutableCopy" or "retain" on object, you must always call "release" or "autorelease" on it. That will prevent any memory leaks.

Apple does not have a publicized amount of memory leaks allowed. It is always safest to eliminate any known memory leaks; plus, it will mean better performance for your customers.


In your second case you are releasing the NSMutableArray but still it store a non zero value although it's no longer for use (To call function OR fetch value).That the reason your if condition got true.

Just remember whenever you call release on any object, Do'nt forget to assign nil to that, So your second code should look like below.

CASE-2

NSMutableArray  *array=[[NSMutableArray alloc]init];
    [array release];
     array = nil;
    if(array)
    {
        NSLog(@"hiiiiiii"); 
    }

There is a simple rule of memory management in Object-C if your alloced or retain any object you must call release on that,

Read memory management Guide from Apple.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜