Iphone target C alloc / release question

I am new to ObjectiveC. I'm having trouble understanding the memory management syntax. My code is below:

NSDate* someDate; someDate=[[NSDate alloc] init]; loop { someDate=[[NSDate alloc] init]; } 

Do I have a memory leak here? or returned NSDate [autorelease] object?

thanks

+4
source share
4 answers

As @DavidKanarek says, you will have leaks.

There are several ways to fix these leaks:

 NSDate* someDate; someDate=[NSDate date]; loop { someDate=[NSDate date]; } 

or

 NSDate* someDate=nil; someDate=[[NSDate alloc] init]; loop { [someDate release]; someDate=[[NSDate alloc] init]; } [someDate release]; 

The first of these is simple code to read, but the second helps reduce memory consumption. If your cycle is not too big, use the first one. If you go through the cycle a thousand times, I would use the second.

Sam

+5
source

You will have many memory leaks. Objects are first saved (not auto-implemented) if they are returned by methods that have a new distribution or copy in the name. [NSDate date] will be auto-implemented. If you post more substantial code, I can give you some help in achieving the whole goal.

Also see Apple Memory Management Guide .

+4
source

This object ownership scheme is implemented through a reference counting system that internally tracks the number of owners of each object. When you claim ownership of an object, you increase the reference counter, and when you do this with the object, you decrease its reference counter. Although its number of links is greater than zero, the object is guaranteed to exist, but as soon as the counter reaches zero, the operating system is allowed to destroy it.

http://rypress.com/tutorials/objective-c/memory-management

But in the latest xcode, it provides ARC (automatic reference counting).
Thus, it will automatically process the reference counter. When a class frees it, free memory for all objects whose contents are inside.

+1
source

You will have many memory leaks.

someDate is a poninter variable and it is assigned a block of memory that you allocate, in this case [[NSDate alloc] init] .

However, in a loop, you assign your pointer variable to another memory box ( someDate=[NSDate date] )

A memory leak occurs because already allocated memory blocks are not issued.

0
source

Source: https://habr.com/ru/post/1301671/


All Articles