开发者

Don't let use -(id)init; method

开发者 https://www.devze.com 2023-03-16 04:38 出处:网络
I\'m developing an app for iPhone 3.1.3. I have the following class: @interface Pattern : NSObject { NSMutableArray* shapes;

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) addO开发者_运维技巧bject:(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?


raise an exception if somebody uses the plain init

- (id)init {
    [NSException raise:@"MBMethodNotSupportedException" format:@"\"- (id)init\" is not supported. Please use the designated initializer \"- (id)initWithNumShapes:screenSize:\""];
    return nil;
}


You can override the init function and give default values from it if you have:

- (id)init {
    return [self initWith....];
}

If you don't want init at all, still override and throw some kind of exception saying not to use init.

- (id)init {
    NSAssert(NO, @"Please use other method ....");
    return nil;
}

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.


Its always the same schema. Just call init on your superclass (NSObject).

- (id) initWithNumShapes:(int)numShapes screenSize:(CGSize)screenSize {
     if(self == [super init]) {
          // Custom Init your properties
          myNumShapes = numShapes;
          myScreenSize = screenSize;
     }
     return self;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号