歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Objective-C中實現覆寫init函數以及在初始化時添加參數

Objective-C中實現覆寫init函數以及在初始化時添加參數

日期:2017/3/1 9:40:27   编辑:Linux編程

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的所有屬性詳解 http://www.linuxidc.com/Linux/2014-03/97744.htm

Objective-C 和 Core Foundation 對象相互轉換的內存管理總結 http://www.linuxidc.com/Linux/2014-03/97626.htm

使用 Objective-C 一年後我對它的看法 http://www.linuxidc.com/Linux/2013-12/94309.htm

10個Objective-C基礎面試題,iOS面試必備 http://www.linuxidc.com/Linux/2013-07/87393.htm

Objective-C適用C數學函數 <math.h> http://www.linuxidc.com/Linux/2013-06/86215.htm

Copyright © Linux教程網 All Rights Reserved