我想在Objective C中创建一个类的只读实例。我有一个向量类,它基本上是x和y位置的浮点数和一些方法。在很多情况下,我需要一个(0,0)-vector,所以我在想,我应该有一个共享的零向量,而不是每次都分配一个新的向量,如下所示:
// 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;这很好用,除了零向量不是只读的,这感觉有点傻。作为一个提示,我想指出的是,这更像是一个想要知道怎么做的问题,而不是一个实际的问题,我不知道它是否会产生一些实际的不同。
发布于 2013-04-17 23:05:32
这取决于您的标准向量应该如何工作。如果你从来不想通过属性来设置x和y,你可以将它们设为只读:
@property (nonatomic, readonly) NSInteger x;
@property (nonatomic, readonly) NSInteger y;如果你的一些向量应该是readwrite的,你可以创建一个只读类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然后,对zeroVector使用Vector,对所有其他对象使用MutableVector。
发布于 2013-04-17 22:40:43
常见的解决方案是让所有实例都是不可变的(参见NSNumber、NSDecimalNumber等),可能会有第二个可变的类(NSString与NSMutableString或NSArray与NSMutableArray)。
发布于 2013-04-17 23:02:25
是否只想阻止其他类更改此类字段?
将它们标记为@private,并确保您的-zeroVector方法返回的类是不可变的(可能是Vector的不可变子类),也就是说,没有任何方法允许其他代码更改其状态。
https://stackoverflow.com/questions/16062957
复制相似问题