Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / 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函数,让其调用iinitWithWidth : (int) w andHeight:(int) h函数。在initWithWidth : (int) w andHeight:(int) h函数中调用init函数初始化对象,然后设置宽度和高度值。使用如下 :View* myViw = [[View alloc] initWithWidth:100 andHeight:30] ;Objective-C中@property的所有属性详解 http://www.linuxidc.com/Linux/2014-03/97744.htmObjective-C 和 Core Foundation 对象相互转换的内存管理总结 http://www.linuxidc.com/Linux/2014-03/97626.htm使用 Objective-C 一年后我对它的看法 http://www.linuxidc.com/Linux/2013-12/94309.htm10个Objective-C基础面试题,iOS面试必备 http://www.linuxidc.com/Linux/2013-07/87393.htmObjective-C适用C数学函数 <math.h> http://www.linuxidc.com/Linux/2013-06/86215.htm本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-09/106150.htm