澄清:這個問題不是關於mutable vs immutable,而是關於超級創建正確類的實例的調用。我沒有想過在基類中使用[[self class] alloc]
,這似乎解決了我的問題。如果沒有更好的出現:)mutableCopyWithZone令人困惑的要求?
If a subclass inherits NSMutableCopying from its superclass and declares
additional instance variables, the subclass has to override mutableCopyWithZone:
to properly handle its own instance variables, invoking the superclass’s
implementation first.
這是非常令人困惑,我會接受在接下來的幾個小時是雁。考慮
@interface Base : NSObject<NSMutableCopying>
@property (nonatomic, assign) NSInteger value ;
@end
@implementation Base
...
@end
@interface Derived : Base<NSMutableCopying>
@property (nonatomic, assign) NSInteger value2 ;
@end
@implementation Derived
- (id) mutableCopyWithZone: (NSZone *) zone {
// Huh ???
Derived * derived = [super mutableCopyWithZone: zone] ;
...
// Huh ??????
derived.value2 = self.value2 ;
return derived ;
}
...
@end
我只是不明白如果我遵循規範這個代碼可能是正確的。
當呼叫[super mutableCopyWithZone: zone]
返回時,我期待基類只爲自己的ivars分配了足夠的空間。沒有辦法可以說明實例需要更多空間來存放自己的ivars。
這是什麼文檔意味着,真的嗎?我應該如何實現這一點?
根據文檔,只有定義「不可變與可變」區別的類應採用NSMutableCopying協議。你有兩個'Derived'和'MutableDerived'類嗎? –
我認爲,Derived是可變類,base是不可變類。 –
如果Base是不可變類,那麼它不會採用NSMutableCopying協議。 –