Objective C でクラスの読み取り専用インスタンスを作成したいと考えています。基本的に x と y の位置といくつかのメソッドに対して浮動小数点であるベクトル クラスがあります。多くの場合、(0, 0)-ベクトルが必要なので、毎回新しいベクトルを割り当てるのではなく、次のようなゼロ ベクトルを共有することを考えていました。
// Don't want to do this all the time (allocate new vector)
compare(v, [[Vector alloc] initWithCartesian:0:0]);
// Want to do this instead (use a shared vector, only allocate once)
compare(v, [Vector zeroVector]);
// My attempt so far
+ (Vector *)zeroVector {
static Vector *sharedZeroVector = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedZeroVector = [[self alloc] initWithCartesian:0:0];
});
return sharedZeroVector;
}
// The problem
v.x = 3;
これは問題なく動作しますが、ゼロ ベクトルが読み取り専用ではないことを除けば、ばかげているように感じます。注意として、これは実際の問題というよりも、知りたい方法の質問であることに言及したいと思います。実際に違いが生じるかどうかはわかりません。