【发布时间】: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的实例? -
ParentClass的init中有什么内容?可以有[self release]吗? -
我如何创建OtherClass对象并不重要,因为我在这个类的一个方法中调用了ivar,所以OtherClass对象肯定是存在的。在 ParentClass 的 init 方法中什么都没有。禁止自我释放,因为我使用的是 ARC。谢谢大家!
标签: ios automatic-ref-counting