Objective-C释放在类别中声明的属性?

我在现有类上有一个类别,它为类添加一个属性和一些方法.
@interface AClass (ACategory) {
    Nsstring *aProperty;
}

@property (nonatomic,retain) Nsstring *aProperty;

@end

在实现文件中,我想在取消分配对象时释放此属性.但是,如果我在这个类中声明dealloc,它将根据我的理解覆盖原始类中的dealloc.当对象被释放时,释放此aProperty的正确方法是什么?

@implementation AClass (ACategory)

@synthesize aProperty;

- (void)dealloc {
    [aProperty release];
    // this will skip the original dealloc method from what I understand
    [super dealloc];
}

@end

解决方法

嗯,这有点问题,因为你的代码错误的.

>您不能在类别中声明实例变量;使用最新的Objective-C ABI,您可以在类扩展中声明新的实例变量(@interface AClass(){// …),但这与类别(@interface AClass(ACategory))不同.
>即使可以,实例变量声明的语法是在@interface行之后用花括号括起来.

您可以在类别中声明属性,但是您必须在不使用新实例变量的情况下定义其存储(因此,@ dynamic而不是@synthesize).

至于你的实际问题,你不能调用重写方法的原始实现,除非你使用方法调配(由method_exchangeImplementations等运行时函数提供便利).无论如何,我建议不要这样做;这真是令人恐惧和危险.

更新:类扩展中的实例变量的说明

类扩展类似于类别,但它是匿名的,必须放在与原始类关联的.m文件中.看起来像:

@interface SomeClass () {
    // any extra instance variables you wish to add
}
@property (nonatomic,copy) Nsstring *aProperty;
@end

它的实现必须在您的类的主要@implementation块中.从而:

@implementation SomeClass
// synthesize any properties from the original interface
@synthesize aProperty;
// this will synthesize an instance variable and accessors for aProperty,// which was declared in the class extension.
- (void)dealloc {
    [aProperty release];
    // perform other memory management
    [super dealloc];
}
@end

因此,类扩展对于将私有实例变量和方法保留在公共接口之外非常有用,但不会帮助您将实例变量添加到您无法控制的类中.覆盖-dealloc没有问题,因为你只是像往常一样实现它,同时包括你在类扩展中引入的实例变量的任何必要的内存管理.

请注意,这些东西仅适用于最新的64位Objective-C ABI.

相关文章

对象的传值与返回说起函数,就不免要谈谈函数的参数和返回值...
从实现装饰者模式中思考C++指针和引用的选择最近在看...
关于vtordisp知多少?我相信不少人看到这篇文章,多半是来自...
那些陌生的C++关键字学过程序语言的人相信对关键字并...
命令行下的树形打印最近在处理代码分析问题时,需要将代码的...
虚函数与虚继承寻踪封装、继承、多态是面向对象语言的三大特...