歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Objective-C中通過分類來擴展現有類

Objective-C中通過分類來擴展現有類

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

在Objective-C中,我們可以以更簡單的方法來擴展現有類以滿足自己的需求。例如,我需要在NSString中添加一個show方法來輸出一個log。

//
@interface NSString (Op)
-(void) show ;
@end

@implementation NSString (Op)

-(void) show
{
NSLog(@" this is NSString show.") ;
}

@end

代碼中的Op為分類名,分類名位於圓括號當中,也可以不使用分類名,例如 @interface NSString () 。我們在該分類中添加了show函數,然後在@implementation中實現了該函數,這樣我們就擴展了NSString,而不需要使用繼承。使用如下 :

NSString* str = [[NSString alloc] init] ;
[str show] ;

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