2012-02-29 69 views
0

我已经使用了下面的代码。僵尸报告:发送到释放实例的消息

MainView.h:

NSString *sCopySource; 
NSString *sFileSource; 

// retain and copy used both for test proposes 
@property (nonatomic, retain) NSString *sCopySource; 
@property (nonatomic, copy) NSString *sFileSource; 

MainView.m:

// Inside the first method: 
sCopySource = [NSString stringWithFormat:@"%@%@", path1, filename]; 
sFileSource = [NSString stringWithFormat:@"%@%@", path2, filename]; 

// Inside the second method: 
[[NSFileManager defaultManager] copyItemAtPath:sCopySource toPath:sFileSource error:&err]; 

而采取错误的启用僵尸的对象sCopySourcesFileSource代码的最后一行:

message sent to deallocated instance 

为什么?标记为retaincopy的属性。如何解决这个问题?

非常感谢您的帮助!

P.S.请不要回答使用ratainrelease方法。他们非常不方便。

回答

2

您已经定义了属性,但是您正在直接写入实例变量。

如果你想使用保留/释放逻辑属性,你需要使用:

self.sCopySource = [NSString stringWithFormat:@"%@%@", path1, filename]; 
    self.sFileSource = [NSString stringWithFormat:@"%@%@", path2, filename]; 

这样一来,所使用做拷贝,并保留方法。

+0

gaige,非常感谢!什么是最好的 - 保留还是复制? – Dmitry 2012-02-29 19:36:29

+0

取决于你在做什么。复制保证你保留的版本不会变异。另一方面,保留对原始对象的引用,如果原始类是可变的,则原始对象可能会变异。通常,保留是足够的和更高效的,但当您使用可能在代码中的其他位置发生变异的值时,复制可能是必需的。 – gaige 2012-02-29 19:38:31

+0

再次感谢! – Dmitry 2012-02-29 19:50:23

相关问题