0

コピーについて疑問があります

概要:

  • Car私は2つのクラスを持っていますMutableCar
  • これらのクラスは両方ともプロトコルに準拠していますNSCopying
  • このメソッドcopyは、次のインスタンスを返します。Car

質問

  1. コンパイラが次のステートメントのコンパイルエラーをスローしないのはなぜですか?

    MutableCar* c2 = [c1 copy];

    コンパイラーを使用すると、Car*をMutableCar*ポインター変数に割り当てることができます。

  2. コンパイル時にこれが見過ごされないようにする方法はありますか?

    以下の例に示すように、これにより実行時にクラッシュが発生する可能性があります。

コード(別のファイル)

注意点-自動参照カウント(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);
}
4

1 に答える 1

1

-[NSObject copy]を返すように宣言されてidいる場合、タイプは任意のオブジェクトポインタに割り当てることができます。そのため、エラーや警告は表示されません。

をオーバーライドcopyして@interface Car、それを返すように宣言するとCar *、偽の割り当てに対してコンパイラ警告が表示されます。

于 2011-12-09T05:01:11.527 に答える