C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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.

大佬总结

以上是大佬教程为你收集整理的Objective-C释放在类别中声明的属性?全部内容,希望文章能够帮你解决Objective-C释放在类别中声明的属性?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: