OC基礎--分類(category) 和 協議(protocol)

OC 中的category分類文件至關於 C#中的部分類;OC 中的protocol協議文件(本質是頭文件)至關於 C#中的接口。今天就簡單說明一下OC中的這兩個文件。ui

因爲視頻中的Xcode版本低,致使了分類文件和協議文件沒有找到,最後百度得知:atom

如圖:Xcode 7.2版本中的category文件和protocol文件都歸類到了Objective-C File 中spa

     

1、category文件:code

做用:能夠擴展自定義類,或者系統類。下面的實例,是擴展了NSString 類,在類中擴展了計算字符串中數字個數的方法:視頻

NSString類的分類的頭文件對象

1 #import <Foundation/Foundation.h>
2 
3 @interface NSString (Number)
4 
5 // 計算字符串中阿拉伯數字的個數
6 - (int) numberCount;
7 
8 @end

NSString類的分類的.m文件blog

 1 #import "NSString+Number.h"
 2 
 3 @implementation NSString (Number)
 4 
 5 // @"abc123"
 6 - (int)numberCount
 7 {
 8     
 9     //[self length];
10     
11     int count = 0;
12     
13     int len = (int) self.length;
14     
15     for (int i = 0; i<len; i++) {
16         // 獲取i位置對應的字符(char)
17        char c = [self characterAtIndex:i];
18         
19        if (c>='0' && c<='9')
20        {
21            count++;
22        }
23     }
24     
25     return count;
26 }
27 
28 @end

main文件:接口

 1 #import <Foundation/Foundation.h>
 2 #import "NSString+Number.h"
 3 
 4 int main(int argc, const char * argv[])
 5 {
 6 
 7     @autoreleasepool {
 8         
 9         NSString *str = @"abc 123fdsf090900sdfds68768867";
10         
11         int count = [str numberCount];
12         
13         NSLog(@"%d", count);
14     }
15     return 0;
16 }

2、protocol文件字符串

做用:聲明一系列方法編譯器

注意點:分類和協議都只能聲明方法,不能聲明成員變量

實例:

 1 // 聲明一系列方法
 2 // 分類和協議都只能聲明方法,不能聲明成員變量
 3 @protocol MyProtocol
 4 
 5 // 默認是@required
 6 - (void) test4;
 7 
 8 @required // test1必須實現的
 9 - (void) test1;
10 
11 @optional  // test二、test3是可選實現的
12 - (void) test2;
13 - (void) test3;
14 
15 @end

 1>類遵照協議

@interface 類名:父類名<協議名稱1,協議名稱2>

@end

2>協議遵照協議

@protocol 協議名稱<其餘協議名稱1,其餘協議名稱2>

@end

3>協議中方法聲明的關鍵字

  (1)@required(默認)

  要求實現,若是沒有實現,會發出警告

  (2)@optional

  不要求實現,

4>定義一個變量的時候,限制這個變量保存的對象遵照某個協議

類名<協議名稱> *變量名;  或者

id<協議名稱> 變量名;

實例:NSObject<MyProtocol> *obj;  或者

id<MyProtocol> obj2;

若是沒有遵照相對應協議,編譯器會警告

5>@property中聲明的屬性也可用來作一個遵照協議的限制

@property (nonatomic,strong) 類名<協議名稱> *屬性;

@property (nonatomic,strong) id<協議名稱> 屬性;

代碼實例:

@property (nonatomic,strong) Dog<MyProtocol> *dog;

@property (nonatomic,strong) id<MyProtocol> dog2;

6>協議可用定義在單獨.h文件中,也可用定義在某各種中

  (1)若是這個協議只用在某各種中,應該把協議定義在該類中

  (2)若是這個協議用在不少類中,就應該定義在單獨文件中

7>分類也可用定義在單獨.h和.m文件中,也可用定義在原來類中

  (1)通常狀況下,都是定義在單獨文件

  (2)定義在原來類中的分類,只要求能看懂語法

相關文章
相關標籤/搜索