【问题标题】:Zombie reports: message sent to deallocated instance僵尸报告:消息发送到解除分配的实例
【发布时间】:2012-03-19 07:22:39
【问题描述】:

我使用了以下代码。

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 的属性。如何解决这个问题?

非常感谢您的帮助!

附:请不要回答使用ratainrelease 方法。它们非常不方便。

【问题讨论】:

    标签: iphone objective-c ios memory-management nsstring


    【解决方案1】:

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

    如果要在属性中使用retain/release逻辑,需要使用:

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

    这样,使用复制和保留的方法。

    【讨论】:

    • 取决于你在做什么。复制保证您保留的版本不会发生变异。另一方面,Retain 保留对原始对象的引用,如果原始类是可变的,则该引用可能会发生变化。通常保留就足够了,而且效率更高,但是当您使用的值可能在代码中的其他位置发生变化时,可能需要复制。
    猜你喜欢
    • 1970-01-01
    • 2014-05-11
    • 2013-06-04
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多