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中@property的所有属性详解

Objective-C 和 Core Foundation 对象相互转换的内存管理总结

使用 Objective-C 一年后我对它的看法

10个Objective-C基础面试题,iOS面试必备

Objective-C适用C数学函数 <math.h>

本文永久更新链接地址:

相关内容

    暂无相关文章