加入收藏 | 设为首页 | 会员中心 | 我要投稿 开发网_开封站长网 (http://www.0378zz.com/)- 科技、AI行业应用、媒体智能、低代码、办公协同!
当前位置: 首页 > 教程 > 正文

Objective-C中达成覆写init函数以及在初始化时添加参数

发布时间:2021-11-20 13:44:22 所属栏目:教程 来源:互联网
导读:Objective-C中在初始化方法中传递参数是惯用法,大致的类型使用方式为: MyClass* obj = [[MyClass alloc] initWithXXX] ; 而默认的初始化只有一个无参的init函数,因此这些initWithXXX函数必须我们手动完成。 看下面的例子 : // 类View @interface View : NS
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] ;

(编辑:开发网_开封站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读