设为首页 加入收藏

TOP

Objective-C中实现覆写init函数以及在初始化时添加参数
2014-11-23 21:31:40 来源: 作者: 【 】 浏览:11
Tags:Objective-C 实现 init 函数 以及 初始 添加 参数

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


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] ;


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Objective-C中通过分类来扩展现有.. 下一篇Android源码分析之单例模式

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: