[英]Objective-C releasing a property declared in a category?
我在現有類上有一個類別,它為類添加了一個屬性和一些方法。
@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
嗯,這有點問題,因為你的代碼是錯誤的。
@interface AClass () {//...
),但這與類別( @interface AClass (ACategory)
)不同。 @interface
行之后用花括號括起來。 您可以在類別中聲明屬性,但是您必須在不使用新實例變量的情況下定義其存儲(因此, @dynamic
而不是@synthesize
)。
至於你的實際問題,你不能調用重寫方法的原始實現,除非你使用方法method_exchangeImplementations
(由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。
另外,您可以使用關聯引用 “ 模擬將對象實例變量添加到現有類 ”。
基本上,您可以添加關聯對象,如下所示:
static void* ASI_HTTP_REQUEST; // declare inside the category @implementation but outside any method
// And within a method, init perhaps
objc_setAssociatedObject(self,
&ASI_HTTP_REQUEST,
request,
OBJC_ASSOCIATION_RETAIN);
並通過發送'nil'釋放相關對象:
// And release the associated object
objc_setAssociatedObject(self,
&ASI_HTTP_REQUEST,
nil,
OBJC_ASSOCIATION_RETAIN);
Apple文檔在這里 。
我花了一段時間才找到,所以我希望它有助於某人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.