#import <Foundation/Foundation.h> @interface EOCRectangle : NSObject<NSCoding> @property (nonatomic , readonly , assign) float width; @property (nonatomic , readonly , assign) float height; -(id)initWithWidth:(float) width andHeight:(float) height; @end #import "EOCRectangle.h" /** * 为对象提供必要信息以便其能完成工做的初始化方法叫作“全能初始化方法” */ @implementation EOCRectangle -(id)initWithWidth:(float) width andHeight:(float) height { if ((self = [super init])){ _width = width; _height = height; } return self; } /** * 初始化设置默认的值 */ //-(id)init //{ // return [self initWithWidth:10.0 andHeight:10.0]; //} /** * 初始化抛出异常 */ -(id)init{ @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"Must use initWithWidth:(float) width andHeight:(float) height instead" userInfo:nil]; } /** * 初始化NSCoding */ -(id)initWithCoder:(NSCoder *)aDecoder{ if ((self = [super init])){ _width = [aDecoder decodeFloatForKey:@"width"]; _height = [aDecoder decodeFloatForKey:@"height"]; } return self; } @end
#import "EOCRectangle.h" @interface EOCSquare : EOCRectangle -(id)initWithDimension:(float)dimension; @end #import "EOCSquare.h" @implementation EOCSquare -(id)initWithDimension:(float)dimension { return [super initWithWidth:dimension andHeight:dimension]; } /** * 覆写超类的全能初始化方法 * */ -(id)initWithWidth:(float) width andHeight:(float) height{ float dimension = MAX(width, height); return [self initWithDimension:dimension]; } /** * 每一个子类的全能初始化方法都应该调用其超类的对应方法,并逐层向上 * * @param aDecoder * * @return */ -(id)initWithCoder:(NSCoder *)aDecoder { if ((self = [super initWithCoder:aDecoder])){ //do something } return self; } @end