mayy00
mayy00

Reputation: 224

Objective C basic memory issue

I've recently started to learn Objective C and I'm kind of confused of some basic memory issues. For example in a tutorial I've seen this:

- (void) setVin: (NSNumber*)newVin {  
    [vin release];  
    vin = [[NSNumber alloc] init];  
    vin = newVin;  
}  

Firstly I am allocating a space for vin and then I'm assigning it to newVin. So what's the point of allocating a new space for vin. After assign, doesn't it leak ?

And another thing is

NSString* s1 = [[NSString alloc] init];
NSString* s2 = [[NSString alloc] init];

When I printed the addresses of these two strings, I've seen that these two pointers hold the same address value. Is it because they hold the same value(empty strings I think), compiler decided to assign them to the same address? Or is it another issue?

Upvotes: 1

Views: 64

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Your first sample comes from a pre-ARC tutorial (i.e. the automatic reference counting is disabled). In ARC you do not need to call release on re-assignment.

There is absolutely no reason to allocate vin like this, ARC or not. Witout ARC, it's a leak; with ARC, it's an unnecessary operation.

Your second sample illustrates the fact that NSStrings are immutable. Since both calls create empty strings, Cocoa returns the same object, knowing that the object cannot be modified.

Upvotes: 3

Max
Max

Reputation: 16709

It is very bad tutorial cause there is definitely a memory leak there. Correct variant is

-(void) setVin: (NSNumber*)newVin {  
    if( newVin != vin ) {
         [vin release];
         vin = [newVin retain];
    }
}

As for the second case NSString is immutable and probably some values are cached internally. So the same value with increased retain count is returned.

Upvotes: 4

Related Questions