我对复制有疑问
概述:
- 我有两节课
Car
,即MutableCar
- 这两个类都符合协议
NSCopying
- 该方法
copy
将返回一个实例Car
问题
为什么编译器不会为以下语句抛出任何编译错误?
MutableCar* c2 = [c1 copy];
编译器允许我将 Car* 分配给 MutableCar* 指针变量
有什么方法可以防止在编译时被忽视吗?
恕我直言,这可能会导致运行时崩溃,如下例所示。
代码(在单独的文件中)
注意事项- 使用自动引用计数 (ARC)
汽车.h
#import<Foundation/Foundation.h>
@interface Car : NSObject <NSCopying>
@property (readonly) int n1;
@end
车
#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
可变汽车
#import"Car.h"
@interface MutableCar : Car
@property int n1; // redeclaration
@property int n2;
@end
可变卡
#import"MutableCar.h"
@implementation MutableCar
@dynamic n1;
@synthesize n2 = _n2;
@end
测试.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);
}