Memory management and performance

If I select an object in the getASprocket method and call it that way, will there be a leak?

Sprocket *sprock = [Sprocket getASprocket];

// store this returned value as an ivar
ivarSprock = [sprock retain];

// release the originally acquired object
[sprock release];

The Sprocket object is allocated and returned as follows:

– (Sprocket *)getASprocket {
    Sprocket *sprocket;

    sprocket = [[Sprocket alloc] init];

    return [sprocket retain];
}

Also, would it change from '[sprocket retain];'inside the aSprocket method to 'return [sprocket autorelease];'degrade performance?

+3
source share
7 answers

Please see this page for a good explanation. Particularly subpage # 7

each saves another created memory object. so let's see what we have:
in getASprocket :

sprocket = [[Sprocket alloc] init];

+ 1

return [sprocket retain];

+ 1

and according to your method:

ivarSprock = [sprock retain];

+ 1

[sprock release];

1

What do we do ? Well, we have to let Sprock go by making it an abstract:

  return [[[Sprocket alloc] init] autorelease]

:

. , dealloc.

0

, . , .

, getASprocket :

return [sprocket retain];

return [sprocket autorelease];

( , ).

, - .

0

. , getASprocket , Sprocet alloc , , , +2 , , +3, +2, +2. s

-(Sprocket*)getASprocket)
{
    return [[[Sprocket alloc] init] autorelease]
} 

0

0

getASprocket: .

sprocket = [[Sprocket alloc] init];
return [sprocket retain];

, alloc/init , .

return [sprocket autorelease];

iVarSprock , .

0

getASprocket Cocoa Cocoa Touch development. , :

ivarSprock = [[ Sprocket alloc ] init ];

// Other Code Here

[ ivarSprock release ];
0

, , , , , . , , , . , , ( ) .

0

, , . ( "sprock" 1 , , dealloc'd):

+ (Sprocket *)getASprocket
{
    return [[[Sprocket alloc] init] autorelease];
}

, . :

  • Objects created with allocor copyhave a hold value of 1 (and must be released)
  • Suppose that all other objects have a save value of 1, but they are auto-implemented (as above)
  • Retain objects you want to save
  • Releaseobjects when you are no longer interested in them (never call dealloc)

Using autodetection pools has a small impact on performance, but it just makes things a lot easier because you don’t need to know the internal implementation details of each method.

0
source

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


All Articles