views:

39

answers:

1

I have a NSString declared in the interface part:

@property (nonatomic, retain) NSString *filePath;

In viewDidLoad I give this a value and when I am trying to call it from one of my custom methods it works for the first time but on the second it crushes. In my opinion filePath was autoreleased during the first call.

I tried a different approach, in my method I have done something like this:

NSString *path = [[[NSString init] alloc] autorelease]; path = [filePath copy];

and this time seems to work, but when checking the retainCount of path it is constantly increasing. The first time the method is called, retainCount is 4 but for the second is 2, third is 3 and so on.

Ok, I understand for filePath to be increasing, because of [copy] but why also for path variable? And why in the first case it didn't worked?

A: 

You don't show all code so it is hard to say anything conclusive. However:

NSString *path = [[[NSString init] alloc] autorelease];
path = [filePath copy];

makes no sense: first you allocate an NSString, and let path point to it. Then you let path point to something else. The NSString is not used (but will be cleaned up by the autorelease).

I see you access filePath just by its name, not through the getter/setter. If you use self.filePath, like

self.filePath = [NSString stringWithFormat:@"..."]; // or any other string

then the retain/release business is handled properly by the setter. To be precise, the difference between filePath = ... and self.filePath = ... is that the latter will retain the object you are assigning.

You should really not be looking at the retainCount to debug things, if you are not very confident you know what's happening under the cocoa hood.

mvds
Thank you for your answer, I am trying to learn as good as I can. I find myself in the following situation:> NSDateFormatter *date_formater=[[NSDateFormatter alloc]init];[date_formater setDateFormat:@"yyyy-MM-dd"];NSLog(@"Count of data : %i",[self.data retainCount]);self.data = [date_formater stringFromDate:[NSDate date]];[date_formater release];NSLog(@"Count of data : %i",[self.data retainCount]);Why the result is:> Count of data : 0Count of data : 2Thnk you in advance.
Parkyprg
Although this is actually a new question, and should be put as one (or, when related, merged into your original question) the answer is that `self.data` is a retained property, so it retains on assignment, and that `[date_formatter stringFromDate:...]` returns strings with a retain count of 1, so that's 2 in total. (when your function is done, it will be 1 again because stringFromDate added it to the autorelease pool)
mvds