Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is retaining a static array makes a leak on non-arc project?

I got a test code below.
(By this example I faced that an interface cannot be statically allocated without retain.)

By this codeblock I understood what really retain is.
I wantto be sure if this makes a leak and should I release it in somewhere else. simply I dont wantto reinitialize each time the array. and made it static.(disadvantage on memory but advantage on speed)

should I release this retained static array somewhere ? is it a safe code or have I totaly remove static and retain words and just init with arrayObjects method classically ? so what may you prefer for me ?

-(NSUInteger)getCoordYByX:(int)ax
{
    NSUInteger ret_=-1;

    static NSArray *coordsX=nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        coordsX=[[NSArray arrayWithObjects:
                      [NSNumber numberWithInt:50],
                      [NSNumber numberWithInt:170],
                      [NSNumber numberWithInt:190],
                      [NSNumber numberWithInt:210],
                      [NSNumber numberWithInt:350],
                      nil]retain];
                      /*it is more longer. cropped for test purposes*/

});
    ret_=[[coordsX objectAtIndex:ax] unsignedIntegerValue];
return  ret_;

}


in conclusion:
why static doesn't keeps the array initial values? and
what If I wantto use retain, may occur a memory leak or not ?
like image 864
Zen Of Kursat Avatar asked Nov 02 '22 14:11

Zen Of Kursat


1 Answers

That's just one way you could declare a global, immutable array of objects.

It is not a leak in the sense that no allocation is unreachable memory. To take that example further (read: to silliness), your program could -retain all those objects and you would still not have a leak by definition of unreachable memory. The array is initialized exactly once and never reassigned, so that initial array will always be accessible to your method, and its elements always reachable via the array.

However, this is memory which cannot be reclaimed until the program terminates (assuming the method body is entered). So, it's really not a design I would encourage (in fact, I avoid this design).

A superior alternative would look more like:

+ (NSUInteger)coordYByX:(int)ax
{
 enum { NCoordsX = 5 };
 const NSUInteger CoordsX[NCoordsX] = { 50,170,190,210,350 };
 assert(ax < NCoordsX && "invalid index"); // handle error as you handle errors
 return CoordsX[ax];
}

This requires zero heap allocations, zero static storage, and zero locks ;)

like image 113
justin Avatar answered Nov 17 '22 07:11

justin