自定义类定义接口时应该定义一个全能初始化方法,所用到的传入参数用只读属性,默认的init初始化可以通过调用全能初始化设置默认参数或抛出异常处理。
父类:
#import "TestRectangle.h"
@interface TestRectangle : NSObject
@property (nonatomic, assign, readonly) CGFloat width;
@property (nonatomic, assign, readonly) CGFloat height;
- (instancetype)initWithWidth:(CGFloat)width height:(CGFloat)height;
@end
@implementation TestRectangle
- (instancetype)initWithWidth:(CGFloat)width height:(CGFloat)height {
if (self = [super init]) {
_width = width;
_height = height;
}
return self;
}
//- (instancetype)init {
// @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"Must use xxx instead" userInfo:nil];
//}
- (instancetype)init {
return [self initWithWidth:5.0 height:10.0];
}
@end
子类:
#import "TestSquare.h"
@interface TestSquare : TestRectangle
- (instancetype)initWithDimension:(CGFloat)dimension;
@end
@implementation TestSquare
- (instancetype)initWithDimension:(CGFloat)dimension {
return [super initWithWidth:dimension height:dimension];
}
- (instancetype)initWithWidth:(CGFloat)width height:(CGFloat)height {
CGFloat dimension = MAX(width, height);
return [self initWithDimension:dimension];
}
@end
这里要注意子类的复写,子类通过复写父类的全能初始化方法,可以覆盖到默认的init方法。想想子类实例的调用过程:init ->父类init->子类的initWithWidth:height:方法->initWithDimension:方法。
所以,子类复写时一定要复写父类的全能初始化方法。
网友评论