【问题标题】:iOS ARC: unexpected 'dealloc' calliOS ARC:意外的“dealloc”调用
【发布时间】:2013-05-27 12:56:06
【问题描述】:

启用 ARC 后,我遇到了 Objective-C 类的问题。

我的课程如下所示:

@interface ParentClass : NSObject {
}

-(void)decodeMethod;
@end

@implementation ParentClass

-(void)decodeMethod{
}

@end

@interface ChilldClass : ParentClass{
  int *buffer;
}
@end

@implementation ChildClass

-(id)init{
  self = [super init];

  if(self != nil){
    buffer = (int *)malloc(20*sizeof(int));
  }

  return self;
}

-(void)dealloc{
  free(buffer);
}

@end

我还有一堂这样的课:

@interface OtherClass : NSObject{
  ParentClass *c;
}
@end

@implementation OtherClass

[...]

-(void)decode{
  c = [[ChildClass alloc] init];

  [c decodeMethod];
}

[...]

@end

如您所见,ChildClass 对象被创建并作为属性存储在OtherClass 中。只要OtherClass 对象是活的,c 指向的ChildClass 对象也应该是活的,不是吗?好吧,我有一个BAD_ACCESS错误,因为在ChildClass初始化之后,在decodeMethod被调用之前,ChildClass中的dealloc方法被自动执行了。

为什么? ARC 已启用,所以dealloc 方法应该在ChildClass 对象被释放时自动调用,但此时不应该发生,因为仍然指向c

有什么帮助吗?

非常感谢!

【问题讨论】:

  • decodeMethod中的ParentClass如何访问其子类中的ivar???
  • 如何创建OtherClass的实例?
  • ParentClassinit 中有什么内容?可以有[self release]吗?
  • 我如何创建OtherClass对象并不重要,因为我在这个类的一个方法中调用了ivar,所以OtherClass对象肯定是存在的。在 ParentClass 的 init 方法中什么都没有。禁止自我释放,因为我使用的是 ARC。谢谢大家!

标签: ios automatic-ref-counting


【解决方案1】:
@interface ChilldClass : ParentClass{

您的问题可能是由ChilldClass 中的拼写错误引起的(错字?)

【讨论】:

  • 不,没有任何错字。谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-04-06
  • 1970-01-01
  • 2011-12-17
  • 2013-10-19
  • 1970-01-01
  • 2012-03-02
  • 2014-01-13
  • 2011-12-06
相关资源
最近更新 更多