コピーについて疑問があります
概要:
Car
私は2つのクラスを持っていますMutableCar
- これらのクラスは両方ともプロトコルに準拠しています
NSCopying
- このメソッド
copy
は、次のインスタンスを返します。Car
質問
コンパイラが次のステートメントのコンパイルエラーをスローしないのはなぜですか?
MutableCar* c2 = [c1 copy];
コンパイラーを使用すると、Car*をMutableCar*ポインター変数に割り当てることができます。
コンパイル時にこれが見過ごされないようにする方法はありますか?
以下の例に示すように、これにより実行時にクラッシュが発生する可能性があります。
コード(別のファイル)
注意点-自動参照カウント(ARC)が使用されます
Car.h
#import<Foundation/Foundation.h>
@interface Car : NSObject <NSCopying>
@property (readonly) int n1;
@end
Car.m
#import"Car.h"
#import"MutableCar.h"
@interface Car() //extension
@property (readwrite) int n1;
@end
@implementation Car
@synthesize n1 = _n1;
- (id) copyWithZone: (NSZone*) pZone
{
Car* newInstance = [[Car alloc] init];
newInstance -> _n1 = _n1;
return(newInstance);
}
@end
MutableCar.h
#import"Car.h"
@interface MutableCar : Car
@property int n1; // redeclaration
@property int n2;
@end
MutableCar.m
#import"MutableCar.h"
@implementation MutableCar
@dynamic n1;
@synthesize n2 = _n2;
@end
test.m
#import"MutableCar.h"
int main()
{
MutableCar* c1 = [[MutableCar alloc] init];
MutableCar* c2 = [c1 copy]; //Car* is being assigned to MutableCar* variable
//Why doesn't the compiler doesn't throw any compilation error ?
//c2.n2 = 20; //At runtime this throws an error, because c2 is not a MutableCar instance
return(0);
}