gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:39:59 26 4
gpt4 key购买 nike

我在现有类上有一个类别,它向该类添加了一个属性和一些方法。

@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

最佳答案

好吧,这有点问题,因为你的代码是错误的。

  1. 不能在类别中声明实例变量;使用最新的 Objective-C ABI,您可以在类扩展中声明新的实例变量 (@interface AClass () {//...),但这不同于类别 ( @interface AClass (ACategory)).
  2. 即使可以,实例变量声明的语法也是将它们括在 @interface 行之后的花括号中。

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


至于您的实际问题,您不能调用覆盖方法的原始实现,除非您使用方法调配(由 method_exchangeImplementations 等运行时函数促进)。无论如何,我建议不要这样做;这真的很可怕和危险。


更新:类扩展中实例变量的解释

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

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

它的实现必须在您的类的主要@implementation block 中。因此:

@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

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

请注意,此内容仅适用于最新的 64 位 Objective-C ABI。

关于Objective-C 释放类别中声明的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4370360/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com