0

我对复制有疑问

概述:

  • 我有两节课Car,即MutableCar
  • 这两个类都符合协议NSCopying
  • 该方法copy将返回一个实例Car

问题

  1. 为什么编译器不会为以下语句抛出任何编译错误?

    MutableCar* c2 = [c1 copy];

    编译器允许我将 Car* 分配给 MutableCar* 指针变量

  2. 有什么方法可以防止在编译时被忽视吗?

    恕我直言,这可能会导致运行时崩溃,如下例所示。

代码(在单独的文件中)

注意事项- 使用自动引用计数 (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);
}
4

1 回答 1

1

-[NSObject copy]声明为 return id,类型可分配给任何对象指针。这就是为什么您不会收到错误或警告的原因。

如果您覆盖copyin 并@interface Car声明它为 return Car *,您将收到关于您的虚假分配的编译器警告。

于 2011-12-09T05:01:11.527 回答