Objective-c中实现覆写init函数以及在初始化时添加参数

objc中在初始化方法中传递参数是惯用法,大致的类型使用方式为 : 

MyClass* obj = [[MyClass alloc] initWithXXX] ;
而默认的初始化只有一个无参的init函数,因此这些initWithXXX函数必须我们手动完成。看下面的例子 :

// 类View
@interface View : NSObject
// 覆写init函数
-(id) init ;

// 绘制函数
-(void) draw ;

-(id) initWithWidth : (int) w andHeight:(int) h ;

@property (nonatomic) int width, height ;

@end

// impl
@implementation View

// 覆写init
-(id) init
{
    return [self initWithWidth:0 andHeight:0] ;
}

// 绘制view
-(void) draw
{
    NSLog(@"draw in view, width = %i, height = %i.", width, height) ;
}

// 初始化, 并且设置初始值
-(id) initWithWidth : (int) w andHeight:(int) h
{
    self = [super init] ;
    if ( self ) {
        width = w ;
        height = h ;
    }
    return self ;
}

@synthesize width, height ;

@end
在View类中,我们添加了 initWithWidth : ( int ) w andHeight:( int ) h 函数, 可以通过该函数初始化对象、传递宽度和高度,并且覆写了init函数,让其调用i

initWithWidth : (int) w andHeight:(int) h函数。在initWithWidth : (int) w andHeight:(int) h函数中调用init函数初始化对象,然后设置宽度和高度值。

使用如下 :

View* myViw = [[View alloc] initWithWidth:100 andHeight:30] ;


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值