簡體   English   中英

如何將符合NSCoding的對象克隆到其子類中?

[英]How can I clone a NSCoding compliant object into a subclass of it?

我有一個NSPopUpButtonCell的自定義子類,以便可以覆蓋其drawBezelWithFrame:inView:方法。

當前,我必須使用initTextCell:pullsDown:創建一個新實例,然后手動復制其所有屬性。 這相當乏味且容易出錯,因為我可能會缺少一些屬性。

我想知道是否可以使用initWithCoder:代替此任務。 我想我應該能夠將現有NSPopUpButtonCell實例中的數據NSPopUpButtonCellNSCoder對象中,例如,導入NSKeyedArchiver ,然后將該數據NSPopUpButtonCell回我的NSPopUpButtonCell子類中。 但是我不知道該怎么做。

如果您的子類所做的全部是重寫方法,即它沒有添加其他字段,那么您可以修改原始NSPopupButtonCell的類或它的副本,使其成為您的子類的實例。

Apple使用此技術實現KVO,在這種情況下,使用動態生成的子類。 如果您的情況是子類是靜態的,這使它變得容易得多,則代碼概述為:

object_setClass(<an NSPopupButtonCell instance>,
                [<your subclass> class]);

如果可以安全地更改原始實例上的類,則根本不涉及對象創建或復制。

請記住, 僅當子類僅更改行為時才可以執行此操作

有關其他說明,請參見此答案

高溫超導

看來我以前使用過錯誤的功能。 隔離非常簡單。

此代碼將NSPopUpButtonCell的屬性復制到其子類中,以便我可以覆蓋其draw ...方法:

@interface MyPopup : NSPopUpButton
@end

@implementation MyPopup
- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        // Set up the archiver
        NSMutableData *data = [NSMutableData data];
        NSKeyedArchiver *arch = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
        // Archive the cell's properties
        [self.cell encodeWithCoder:arch];
        [arch finishEncoding];
        // Set up the unarchiver
        NSKeyedUnarchiver *ua = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        // Create a subclass of the cell's class, using the same properties
        MyCell *newCell = [[MyCell alloc] initWithCoder:ua];
        // Assign the new subclass object as the NSButton's cell.
        self.cell = newCell;
    }
    return self;
}

此處顯示了另一種使用自定義NSButtonCell子類的更簡潔的方法使用NSPopupButton的全角文本,沒有箭頭

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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