0
votes

I was learning about property, I read various documents but still not clear about how property works and came across scenario which confused me.I created one sample app in which I created one property as follows:

@property(nonatomic,retain)NSString *strValue;

and synthesize it:

@synthesize strValue;

1)First Scenario:

In viewDidLoad I wrote:

strValue = [[NSString stringWithFormat:@"value"] retain];

In dealloc I wrote:

NSLog(@"str value : %@",self.strValue);
[self.strValue release];

It worked fine without any leak.My question here is: What happened to memory which is retained when I created retained property strValue(@property(nonatomic,retain)NSString *strValue;)?

2)Second Scenario:

In viewDidLoad I wrote:

self.strValue = [[NSString stringWithFormat:@"value"] retain];

In dealloc I wrote:

NSLog(@"str value : %@",self.strValue);
[self.strValue release];

It showed memory leak at self.strValue = [[NSString stringWithFormat:@"value"] retain] line.Question here is:Why it is showing memory leak here?Will this line is not equivalent to following lines of code:

[strValue release];
[strValue retain];

3)Third Scenario: In viewDidLoad I wrote:

self.strValue = [NSString stringWithFormat:@"value"];

In dealloc I wrote:

NSLog(@"str value : %@",self.strValue);
[self.strValue release];

It worked fine without any memory leak or dangling reference, how? Can anyone explain how property actually works?How memory is assigned and released when we use property?

1

1 Answers

1
votes

First question,

Since you are setting the instance to the variable itself and not to the property then you will have to allocate (or retain) the given instance, if you gave this variable an autoreleased object, later on the property will become zombie

Second question

No its not similar since the property already retains the instance, another retain will increase the retain count by an additional one, so you will have an additional retain count that will not be released ever.

Third question

As i said earlier the property will retain the instance so there will be no problem passing an auto released instance to it

here is a sample retain property setter

- (void) setProperty:(BookItem *)prop
{
    if(_property != prop)
    {       
        [_property release];//release old
        _property = prop;
        [prop retain]; //retain new
    }
}