不要让使用 -(id)init;方法
我正在为 iPhone 3.1.3 开发一个应用程序。
我有以下课程:
@interface Pattern : NSObject {
NSMutableArray* shapes;
NSMutableArray* locations;
CGSize bounds;
}
@property (nonatomic, retain, readonly) NSMutableArray* shapes;
@property (nonatomic, retain, readonly) NSMutableArray* locations;
- (id) initWithNumShapes:(int)numShapes screenSize:(CGSize)screenSize;
- (void) addObject:(Object2D*) newObject;
@end
我不想让程序员使用 -(id)init;
因为我需要在每次初始化时设置我的字段(形状、位置、边界)。
我不想让程序员使用这个:
Pattern* myPattern = [[Pattern alloc] init];
我知道如何实现:
- (id) initWithNumShapes:(int)numShapes screenSize:(CGSize) screenSize{
if (self = [super init]) {
shapes = [NSMutableArray arrayWithCapacity:numShapes];
locations = [NSMutableArray arrayWithCapacity:numShapes];
bounds = screenSize;
}
return (self);
}
我该怎么做?
I'm developing an app for iPhone 3.1.3.
I have the following class:
@interface Pattern : NSObject {
NSMutableArray* shapes;
NSMutableArray* locations;
CGSize bounds;
}
@property (nonatomic, retain, readonly) NSMutableArray* shapes;
@property (nonatomic, retain, readonly) NSMutableArray* locations;
- (id) initWithNumShapes:(int)numShapes screenSize:(CGSize)screenSize;
- (void) addObject:(Object2D*) newObject;
@end
I don't want to let programmers use -(id)init;
because I need to setup my fields (shape, locations, bounds) on every initialization.
I don't want to let programmers use this:
Pattern* myPattern = [[Pattern alloc] init];
I know how to implement:
- (id) initWithNumShapes:(int)numShapes screenSize:(CGSize) screenSize{
if (self = [super init]) {
shapes = [NSMutableArray arrayWithCapacity:numShapes];
locations = [NSMutableArray arrayWithCapacity:numShapes];
bounds = screenSize;
}
return (self);
}
How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果有人使用普通的
init
则引发异常raise an exception if somebody uses the plain
init
如果您有以下情况,您可以重写 init 函数并为其提供默认值:
如果您根本不需要 init,仍然重写并抛出某种异常,表示不使用 init。
如果有人尝试调用
init
,这总是会给出异常。我建议使用前一种情况,并有一些默认值。
You can override the init function and give default values from it if you have:
If you don't want init at all, still override and throw some kind of exception saying not to use init.
This will always give an exception if anyone tried to call
init
.I would suggest to use the former case though, and have some default values.
它始终是相同的架构。只需在您的超类(NSObject)上调用 init 即可。
Its always the same schema. Just call init on your superclass (NSObject).