簡體   English   中英

Objective-C釋放在類別中聲明的屬性?

[英]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

嗯,這有點問題,因為你的代碼是錯誤的。

  1. 您不能在類別中聲明實例變量; 使用最新的Objective-C ABI,您可以在類擴展中聲明新的實例變量( @interface AClass () {//... ),但這與類別( @interface AClass (ACategory) )不同。
  2. 即使你可以,實例變量聲明的語法是它們在@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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM