NSString和retainCount问题
我在接口部分声明了一个 NSString:
@property(非原子,保留)NSString *filePath;
在 viewDidLoad 中,我给它一个值,当我尝试从我的一个自定义方法调用它时,它第一次起作用,但第二次它就崩溃了。在我看来,filePath 是在第一次调用期间自动释放的。
我尝试了一种不同的方法,在我的方法中我做了这样的事情:
NSString *path = [[[NSString init] alloc] autorelease]; path = [文件路径副本];
这次似乎有效,但是当检查路径的retainCount时,它不断增加。 第一次调用该方法时,retainCount 为 4,但第二次为 2,第三次为 3,依此类推。
好的,我理解 filePath 会因为 [copy] 而增加,但为什么路径变量也会增加? 为什么在第一种情况下它不起作用?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有显示所有代码,因此很难得出结论。然而:
没有意义:首先分配一个 NSString,并让
path
指向它。然后你让path指向其他东西。 NSString 未被使用(但会被自动释放清理)。我看到您仅通过名称访问
filePath
,而不是通过 getter/setter 。如果您使用 self.filePath ,那么保留/释放业务将由 setter 正确处理。准确地说,
filePath = ...
和self.filePath = ...
之间的区别在于后者会保留您的对象正在分配。如果您不太有信心知道可可引擎盖下发生了什么,您真的不应该查看保留计数来调试。
You don't show all code so it is hard to say anything conclusive. However:
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 useself.filePath
, likethen the retain/release business is handled properly by the setter. To be precise, the difference between
filePath = ...
andself.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.