2013-04-17 63 views
3

我想在Objective C中創建一個類的只讀實例。我有一個向量類,它基本上是爲x和y位置以及一些方法漂浮的。在很多情況下,我需要一個(0,0)維矢量,所以我想的不是分配每一次,我將有一個共享的零矢量一個新的,這樣的事情:Objective C共享只讀實例類

// 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; 

這工作正常,除了零矢量不是隻讀的,這感覺很愚蠢。作爲一個說明,我想提一提的是,這更像是一個想知道怎麼樣的問題,而不是一個實際的問題,我不知道它是否會產生一些實際的差異。

+0

你是什麼意思「它不是隻讀」?僅供參考,您**不能**做[Vector setZeroVector:foo];',因爲沒有實現。 – 2013-04-17 14:37:49

+0

一個更簡單的解決方法:你可以在vector類中創建一個 - (BOOL)isZero方法,然後檢查coord屬性,如if(self.x == 0 && ...)。這不回答你的問題,但可能是一個更清潔,更快的解決方案,您的問題:) –

回答

4

取決於你的標準載體應該如何工作。如果你從來沒有要設置通過屬性x和y,你可以只讓他們只讀:

@property (nonatomic, readonly) NSInteger x; 
@property (nonatomic, readonly) NSInteger y; 

如果一些載體應該是讀寫,你可以創建一個只讀類Vector和派生類MutableVector:

@interface Vector : NSObject 
    @property (nonatomic, readonly) NSInteger x; 
    @property (nonatomic, readonly) NSInteger y; 
@end 

@interface MutableVector : Vector 
    @property (nonatomic) NSInteger x; 
    @property (nonatomic) NSInteger y; 
@end 

然後,您將使用Vector作爲zeroVector和MutableVector用於所有其他作品。

5

常見的解決辦法是具有所有實例不可變的(見NSNumberNSDecimalNumber等),可能具有第二可變類(NSString VS NSMutableStringNSArray VS NSMutableArray)。

0

你只是想防止其他類改變這個類字段嗎?

它們標記爲@private和(如Sulthan寫入),確保一流的,你-zeroVector方法返回是不變的(的Vector也許是一個不變的子類),即有沒有方法,將允許其他代碼來改變它的狀態。請參閱related question about Obj-C private fields