標籤:
category是Objective-c裡面最常用的功能之一。
category可以為已經存在的類增加方法,而不需要增加一個子類。
類別介面的標準文法格式如下:
[cpp] view plaincopy
- #import "類名.h"
- @interface 類名 (類別名)
- //新方法的聲明
- @end
類別實現如下:
[cpp] view plaincopy
- #import "類名類別名.h"
- @implementation 類名 (類別名)
- //新方法實現
- @end
這跟類的定義非常類似,區別就是category沒有父類,而且在括弧裡面有category的名子。名字可以隨便取。
如:我們如果想在NSString上增加一個方法判斷它是否是一個URL,那就可以這麼做:
[cpp] view plaincopy
- #import …
- @interface NSString (Utilities)
- - (BOOL) isURL;
- @end
類別實現:
[cpp] view plaincopy
- #import "NSStringUtilities.h"
- @implementation NSString (Utilities)
- - (BOOL) isURL{
- if( [self hasPrefix:@"http://"] )
- return YES;
- else
- return NO;
- }
- @end
使用方法:
[cpp] view plaincopy
- NSString* string1 = @"http://www.csdn.net";
- NSString* string2 = @"Pixar";
-
- if( [string1 isURL] )
- NSLog(@"string1 is a URL");
- else
- NSLog(@"string1 is not a URL");
-
- if( [string2 isURL] )
- NSLog(@"string2 is a URL");
- else
- NSLog(@"string2 is not a URL");
Objective-c Category(類別)