OC高效率52之提供「全能初始化」方法

#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
相關文章
相關標籤/搜索