【问题标题】:Deallocation of object对象的重新分配
【发布时间】:2013-10-08 19:13:42
【问题描述】:

我有一个继承自 MapKit 的 MKPlacemark 类的对象。我在 ViewController 的 viewDidLoad 期间启动了一个方法,该方法创建了这样的对象(alloc + init)并将其传递给 MapView,如下所示

[self.mapView addAnnotation:<my instance of my class inheriting MKPlacemark>]

但是,当我启动程序时,我收到以下错误消息:

An instance 0x9a5d650 of class <name of my class> was deallocated while key value   
observers were still registered with it. Observation info was leaked, and may even 
become mistakenly attached to some other object. Set a breakpoint on 
NSKVODeallocateBreak to stop here in the debugger.

请注意,我使用的是 ARC。谁能告诉我如何避免这种释放?

谢谢!

编辑:我的问题不是警告本身,而是我不希望这个对象在那一刻被释放......

EDIT2:类的代码如下

.h 文件如下所示

@interface OPTCreatureMark : MyMark

@property (nonatomic, assign) CLLocationCoordinate2D coordinate;

-(id)initWithCoordinate:(CLLocationCoordinate2D)coordinate; 
@end

还有 .m 之类的

@implementation MyMark

@synthesize coordinate;

-(id) initWithCoordinate:(CLLocationCoordinate2D)coordinate_ {
    if (self = [super initWithCoordinate:coordinate_ addressDictionary:nil]) {

        self.coordinate=coordinate_;

        return self;
    } else {
        return nil;
    }
}
@end

【问题讨论】:

  • 你在课堂上使用 KVO 吗?
  • 哪个类被释放了?屏幕上的视图控制器?屏幕上的景色?该控制器中的模型?另一个控制器使用的模型?此警告意味着您忘记在某处removeObserver:forKeyPath:
  • 是我的类继承了 MKPlacemark。
  • 你能把代码提供给你的MKPlacemark-conforming 类吗?
  • 您能否显示代码,您可能正在向这些地标添加观察者?

标签: ios objective-c memory-management


【解决方案1】:

如果您确实在使用 KVO,听起来您需要在对象的 dealloc 方法中删除观察者,如下所示:

[self removeObserver:self.myDelegate forKeyPath:@"zoom"];

否则消息可能会发送到您的类的已释放实例(由于已被释放而无法再响应),从而导致异常。

【讨论】:

  • 我建议在 dealloc 之前这样做。在dealloc期间,对象图将处于不连贯状态。如果对象图期间的观察者文件崩溃,可能会发生不好的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-21
  • 1970-01-01
  • 2013-01-17
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 2012-08-02
相关资源
最近更新 更多