开发者

NSString and retainCount question

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 lik开发者_如何学运维e 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜